JAVA 泛型T V 等一些方法
程序员文章站
2024-03-14 18:32:10
...
public class TextClass<T> {
private T mv;
private Type mType;
private void getSuperclassTypeParameter() throws IllegalAccessException, InstantiationException {
Type superclass = getClass().getGenericSuperclass();
Type[] params = ((ParameterizedType) superclass).getActualTypeArguments();
mv = (T) ((Class) params[0]).newInstance();
}
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}
}
待整理
public void mains123() { Method[] methods = getClass().getDeclaredMethods(); for (Method method : methods) { System.out.println("method:" + method.getName());// 方法名 // //////////////方法的参数 System.out.println(" paramTypeType: "); Type[] paramTypeList = method.getGenericParameterTypes();// 方法的参数列表 for (Type paramType : paramTypeList) { System.out.println(" " + paramType);// 参数类型 if (paramType instanceof ParameterizedType)/**//* 如果是泛型类型 */ { Type[] types = ((ParameterizedType) paramType) .getActualTypeArguments();// 泛型类型列表 System.out.println(" TypeArgument: "); for (Type type : types) { System.out.println(" " + type); } } } // //////////////方法的返回值 System.out.println(" returnType: "); Type returnType = method.getGenericReturnType();// 返回类型 System.out.println(" " + returnType); if (returnType instanceof ParameterizedType)/**//* 如果是泛型类型 */ { Type[] types = ((ParameterizedType) returnType) .getActualTypeArguments();// 泛型类型列表 System.out.println(" TypeArgument: "); for (Type type : types) { System.out.println(" " + type); } } }}