public <T> T create(Class<T> type) {
return create(type, null, null);
}
@SuppressWarnings("unchecked")
public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
//根据接口创建具体的类
//1.解析接口
Class<?> classToCreate = resolveInterface(type);
// we know types are assignable
//2.实例化类
return (T) instantiateClass(classToCreate, constructorArgTypes, constructorArgs);
}
//2.实例化类
private <T> T instantiateClass(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
try {
Constructor<T> constructor;
//如果没有传入constructor,调用空构造函数,核心是调用Constructor.newInstance
if (constructorArgTypes == null || constructorArgs == null) {
constructor = type.getDeclaredConstructor();
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
return constructor.newInstance();
}
//如果传入constructor,调用传入的构造函数,核心是调用Constructor.newInstance
constructor = type.getDeclaredConstructor(constructorArgTypes.toArray(new Class[constructorArgTypes.size()]));
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
return constructor.newInstance(constructorArgs.toArray(new Object[constructorArgs.size()]));
} catch (Exception e) {
//如果出错,包装一下,重新抛出自己的异常
StringBuilder argTypes = new StringBuilder();
if (constructorArgTypes != null) {
for (Class<?> argType : constructorArgTypes) {
argTypes.append(argType.getSimpleName());
argTypes.append(",");
}
}
StringBuilder argValues = new StringBuilder();
if (constructorArgs != null) {
for (Object argValue : constructorArgs) {
argValues.append(String.valueOf(argValue));
argValues.append(",");
}
}
throw new ReflectionException("Error instantiating " + type + " with invalid types (" + argTypes + ") or values (" + argValues + "). Cause: " + e, e);
}
}
反射创建对象(Mybatis 对象工厂类实现)
最新推荐文章于 2022-12-20 17:15:02 发布