来自其父级在java中的Builder类的Init对象

时间:2017-11-10 13:18:01

标签: java

我有一个父类,如:

public abstract class ParentObject {

    public abstract String[] fields();

    public abstract String tableName();

}

这样的儿童班:

public class MyObject extends ParentObject {


    String id = "";
    String name = "";

    public MyObject(Map<String, Object> map){
        this.id = map.get("id").toString();
        this.name = map.get("name").toString();
    }


    @Override
    public String[] fields() {
        return new String[]{"id","name"};
    }

    @Override
    public String tableName() {
        return "testTable";
    }

}

我想在ParentObject中创建一个Builder类,以便能够初始化所有子类,如:

MyObject object = new MyObject.Builder().getById("objectId").build();

我尝试使用泛型,但我找不到我想要的东西,我需要一个类似于的类:

public static class Builder{

    public Builder(){

    }

    public Builder getById(){
        //some server codes here
        return Builder.this;
    }

    public T build(){
        return new T(map);
    }
}

我需要知道我是否可以使用这样的泛型:

return new T();

如果不是,我该怎么做?

1 个答案:

答案 0 :(得分:0)

基本上你需要以下内容:

public <T extends ParentObject> T build(Class<T> targetClass) throws IllegalAccessException, InstantiationException {
    T t = targetClass.newInstance();
    t.tableName(); // can access the method
    return t;
}

您需要传递targetClass build(MyObject.class)