实例化具有无参数构造函数的泛型对象
public <T> T getNewObject(Class<T> cls) {
T t&#61;null;
try {
t &#61; cls.newInstance();
} catch (InstantiationException|IllegalAccessException e) {
e.printStackTrace();
}
return t;
}
调用
String i &#61;getNewObject(String.class);
这种方法需要泛型类具有一个无参数构造函数
实例化没有无参数构造函数的泛型对象
public <T> T getNewObject(Constructor<T> cls, double d) {
T t &#61; null;
try {
t &#61; cls.newInstance(d);
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
return t;
}
调用
con &#61; Float.class.getConstructor(double.class);
Float k &#61;getNewObject(con,10.0);
这种方法先确定使用泛型类的哪一个构造函数&#xff0c;再通过该构造函数newInstance实例出来。
通用的实例泛型对象&#xff08;无需区别是否有无参数构造函数&#xff09;
通过反射动态创建泛型实例
public class BasePresenter<V extends BaseView,M extends BaseModel>{
private M mModel;
public void attach(){
Type genType &#61; getClass().getGenericSuperclass();
Type[] types &#61; ((ParameterizedType) genType).getActualTypeArguments();
try {
mModel&#61; (M) ((Class)types[1]).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public M getModel(){
return mModel;
}
}
getSuperclass和 getGenericSuperclass的区别
- getSuperclass返回直接继承的父类不包括泛型参数
- getGenericSuperclass返回直接继承的父类包含泛型参数
getInterfaces 和 getGenericInterface 的区别
- getInterfaces 返回直接实现的接口&#xff08;不显示泛型参数&#xff09;
- getGenericInterface 返回直接实现的接口&#xff08;显示泛型参数&#xff09;
封装成工具类
public class ReflectionUtil {
public static String getClassName(Type type){
if(type&#61;&#61;null){
return "";
}
String className &#61; type.toString();
if (className.startsWith("class")){
className&#61;className.substring("class".length());
}
return className;
}
public static Type getParameterizedTypes(Object o){
Type superclass &#61; o.getClass().getGenericSuperclass();
if(!ParameterizedType.class.isAssignableFrom(superclass.getClass())) {
return null;
}
Type[] types &#61; ((ParameterizedType) superclass).getActualTypeArguments();
return types[0];
}
public static Type getInterfaceTypes(Object o){
Type[] genericInterfaces &#61; o.getClass().getGenericInterfaces();
return genericInterfaces[0];
}
public static boolean hasDefaultConstructor(Class<?> clazz) throws SecurityException {
Class<?>[] empty &#61; {};
try {
clazz.getConstructor(empty);
} catch (NoSuchMethodException e) {
return false;
}
return true;
}
public static Object newInstance(Type type)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class<?> clazz &#61; getClass(type);
if (clazz&#61;&#61;null) {
return null;
}
return clazz.newInstance();
}
public static Class<?> getClass(Type type)
throws ClassNotFoundException {
String className &#61; getClassName(type);
if (className&#61;&#61;null || className.isEmpty()) {
return null;
}
return Class.forName(className);
}
}