2 bai ban bai_ban 于 2015.06.13 21:17 提问

JAVA 反射构造函数带泛型参数的类

JAVA 反射构造函数带泛型参数的类
比如说:

 public class User<T extends Person> {
    private T rootType;

    public User(T rootType){
        this.rootType = rootType;
    }   

    @Override
    public String toString() {
        return "User [rootType=" + rootType + "]";
    }

}

public class Work extends Person {

    @Override
    public String toString() {
        return "Work [getClass()=" + getClass() + ", hashCode()=" + hashCode()
                + ", toString()=" + super.toString() + "]";
    }

}

public class Person {

    @Override
    public String toString() {
        return "Person []";
    }

}

我想要构造一个User(work), 如何构造?

 public static <T extends Person> T getInstance() {
        String className = "com.aaa.reflection.utils.User";
        Class clazz;
        try {
            clazz = Class.forName(className);
            Constructor<?>[] cons = clazz.getConstructors();
            Constructor<?> con = cons[0];
            Object initargs = Work.class;
            T obj = (T) con.newInstance(initargs);
            System.out.println(obj.toString());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

3个回答

caozhy
caozhy   Ds   Rxr 2015.06.13 22:34
u011133213
u011133213   2015.06.14 10:25

建议你还是去找本JAVA基础书籍来看看!

cuiwei1026522829
cuiwei1026522829   Ds   Rxr 2015.06.14 15:36
Csdn user default icon
上传中...
上传图片
插入图片