目的
在接口中实现如下方法,获取T的实例化对象
public interface Base<T> {
default T getInstanceOfT() {
T bean;
/*...代码*/
return bean;
}
}
准备工具类
public class ReflectUtils {
private ReflectUtils(){
}
public static <T> T newBean(Class<T> clazz){
T t = null;
try {
t = clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
log.error(e.getMessage(),e);
}
return t;
}
public static ParameterizedType getParameterizedType( Class<?> interfaceType, Class<?> implementationClass) {
if (implementationClass == null) {
// If the super class is Object parent then return null
return null;
}
// Get parameterized type
ParameterizedType currentType = getParameterizedType(interfaceType, implementationClass.getGenericInterfaces());
if (currentType != null) {
// return the current type
return currentType;
}
Class<?> superclass = implementationClass.getSuperclass();
return getParameterizedType(interfaceType, superclass);
}
public static ParameterizedType getParameterizedType(Class<?> superType, Type... genericTypes) {
ParameterizedType currentType = null;
for (Type genericType : genericTypes) {
if (genericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericType;
if (parameterizedType.getRawType().getTypeName().equals(superType.getTypeName())) {
currentType = parameterizedType;
break;
}
}
}
return currentType;
}
}
最终实现
interface Base<T> {
default T getinstanceOfT(){
T bean;
ParameterizedType parameterizedType = getParameterizedType(BaseDTO.class, getClass());
if(parameterizedType==null)
return null;
Class<T> clazz = (Class<T>) parameterizedType.getActualTypeArguments()[0];
bean = newBean(clazz);
return bean;
}
}