泛型例項化,引數例項化
阿新 • • 發佈:2020-12-19
/** * 初始化 * @param parameter 引數 * @return 例項化的物件 */ protected H init(String parameter){ Type superClass = getClass().getGenericSuperclass();
//獲取第二個列舉物件 Type type = ((ParameterizedType) superClass).getActualTypeArguments()[1]; Class<?> clazz = getRawType(type);try {
//獲取建構函式列表 final Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
//獲取建構函式引數,定義例項化物件的引數型別 final Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(declaredConstructors[0].getParameterTypes()); declaredConstructor.setAccessible(true); return (H) declaredConstructor.newInstance(parameter, "qeqweqwew"); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new ServiceException(e.getMessage(),e.getCause()); } }
/*** type不能直接例項化物件,通過type獲取class的型別,然後例項化物件 * @param type 型別 * @return 物件 */ public static Class<?> getRawType(Type type) { if (type instanceof Class) { return (Class<?>) type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type rawType = parameterizedType.getRawType(); return (Class<?>) rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType) type).getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { return Object.class; } else if (type instanceof WildcardType) { return getRawType(((WildcardType) type).getUpperBounds()[0]); } else { String className = type == null ? "null" : type.getClass().getName(); throw new IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <" + type + "> is of type " + className); } }
https://www.cnblogs.com/tiancai/p/9603050.html
https://www.cnblogs.com/duanweishi/p/4480163.html