Java通过反射获取泛型实例对象

获取泛型实例代码
public static  T getInstance(Object o) {
    try {
        Type type = o.getClass().getGenericSuperclass();
        if (type == null) {
            return null;
        }
        ParameterizedType parameterizedType = null;
        if (type instanceof ParameterizedType) {
            parameterizedType = (ParameterizedType) type;
        }
        if (parameterizedType == null) {
            return null;
        }
        Type[] types = parameterizedType.getActualTypeArguments();
        if (types.length == 0) {
            return null;
        }
        Type realType = parameterizedType.getActualTypeArguments()[0];
        Class clz = (Class) realType;
        return clz.newInstance();

    } catch (InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

测试:

public class UserTest {
    protected T test;
    public UserTest() {
        this.test = createTest();
    }
    private T createTest() {
        return Util.getInstance(this);
    }
}
public class Test {
    public void getData() {
        System.out.println("getData");
    }
    public void request() {
        System.out.println("request");
    }

}
public class Main extends UserTest {
    private Test get(){
        return test;
    }
    public static void main(String[] args) {
        new Main().get().request();
        new Main().get().getData();       
     }

}

 

你可能感兴趣的:(Java,反射,泛型)