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;
    }
查看全部
bai_ban
bai_ban
2015/06/13 13:17
  • java
  • 构造函数
  • 泛型
  • 反射
  • 点赞
  • 收藏
  • 回答
    私信

3个回复