如何使用Class.forName的结果创建泛型类的实例

时间:2012-06-04 15:25:15

标签: java generics reflection

我可以在不知道其类型参数的情况下创建泛型类的实例吗?我只有'class'类型,它是从Class.forName(classname);

获得的
//generic class

public class MappedField<T> extends Field {
    private T value;
    private String sourceName;

public MappedField(String name, String sourceName, FieldType type){
    super(name, type);
    this.sourceName = sourceName;
}    

public MappedField(String name, String sourceName, FieldType type, boolean key){
    super(name, type, key);
    this.sourceName = sourceName;
}

}

//here's my situation

    String columnName = field.getSourceName() != null ? field.getSourceName() : field.getName();
            Class c = Class.forName(field.getType().getFullClassName());            

            //I need like that if `field.getType() = "Integer"`: `MappedField<Integer> objField = new MappedField<Integer>(field)`;
            MappedField objField = new MappedField(field);

            objField.setValue(getField(c, rset, columnName));            
            object.getValues().add(objField);

修改 这就像我有“java.lang.Integer”并想要获得MappedField

1 个答案:

答案 0 :(得分:1)

通用类型将在成功编译时从类和接口中删除。在运行时,无法检测泛型类型。

参考链接: Use reflection to create a generic parameterized class in Java