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 对象工厂类实现)
最新推荐文章于 2024-11-13 15:55:56 发布
本文介绍了一种使用Java反射机制创建对象的方法。通过解析接口并利用反射API实例化具体类,支持带参或无参构造。当构造过程中出现错误时,会捕获异常并抛出自定义的ReflectionException。

1013

被折叠的 条评论
为什么被折叠?



