public class BasePresenter<V extends BaseView,M extends BaseModel>{
private M mModel;
public void attach(){
Type genType = getClass().getGenericSuperclass();
Type[] types = ((ParameterizedType) genType).getActualTypeArguments();
try {
mModel= (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 返回直接实现的接口(不显示泛型参数)
- getGenericInterface 返回直接实现的接口(显示泛型参数)
封装成工具类
public class ReflectionUtil {
public static String getClassName(Type type){
if(type==null){
return "";
}
String className = type.toString();
if (className.startsWith("class")){
className=className.substring("class".length());
}
return className;
}
public static Type getParameterizedTypes(Object o){
Type superclass = o.getClass().getGenericSuperclass();
if(!ParameterizedType.class.isAssignableFrom(superclass.getClass())) {
return null;
}
Type[] types = ((ParameterizedType) superclass).getActualTypeArguments();
return types[0];
}
public static Type getInterfaceTypes(Object o){
Type[] genericInterfaces = o.getClass().getGenericInterfaces();
return genericInterfaces[0];
}
public static boolean hasDefaultConstructor(Class<?> clazz) throws SecurityException {
Class<?>[] empty = {};
try {
clazz.getConstructor(empty);
} catch (NoSuchMethodException e) {
return false;
}
return true;
}
public static Object newInstance(Type type)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class<?> clazz = getClass(type);
if (clazz==null) {
return null;
}
return clazz.newInstance();
}
public static Class<?> getClass(Type type)
throws ClassNotFoundException {
String className = getClassName(type);
if (className==null || className.isEmpty()) {
return null;
}
return Class.forName(className);
}
}