001 ObjectFactory
ObjectFactory: 对象工厂,在框架内容使用该对象进行对象的创建.
public interface ObjectFactory {
// 给对象工厂设置一些属性值
void setProperties(Properties properties);
// 使用类型字节码创建对象
<T> T create(Class<T> type);
// 使用构造函数创建对象
<T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs);
// 判断一个类型是否是一个集合类型.
<T> boolean isCollection(Class<T> type);
}
在框架内容,只有一个默认的实现类,一般情况下,我们也会使用这个实现类来完成功能.
DefaultObjectFactory:
@Override
public void setProperties(Properties properties) {
// no props for default
}
我们看到默认的对象工厂是不支持属性配置的.
我们看看到底是怎么创建对象的.
private <T> T instantiateClass(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
try {
Constructor<T> constructor;
if (constructorArgTypes == null || constructorArgs == null) {
constructor = type.getDeclaredConstructor();
try {
return constructor.newInstance();
} catch (IllegalAccessException e) {
if (Reflector.canControlMemberAccessible()) {
constructor.setAccessible(true);
return constructor.newInstance();
} else {
throw e;
}
}
}
constructor = type.getDeclaredConstructor(constructorArgTypes.toArray(new Class[constructorArgTypes.size()]));
try {
return constructor.newInstance(constructorArgs.toArray(new Object[constructorArgs.size()]));
} catch (IllegalAccessException e) {
if (Reflector.canControlMemberAccessible()) {
constructor.setAccessible(true);
return constructor.newInstance(constructorArgs.toArray(new Object[constructorArgs.size()]));
} else {
throw e;
}
}
} catch (Exception e) {
String argTypes = Optional.ofNullable(constructorArgTypes).orElseGet(Collections::emptyList)
.stream().map(Class::getSimpleName).collect(Collectors.joining(","));
String argValues = Optional.ofNullable(constructorArgs).orElseGet(Collections::emptyList)
.stream().map(String::valueOf).collect(Collectors.joining(","));
throw new ReflectionException("Error instantiating " + type + " with invalid types (" + argTypes + ") or values (" + argValues + "). Cause: " + e, e);
}
}
上面的代码十分简单,首先判断创建的参数是否指明有构造函数参数,如果不存在的话,我们就使用默认的构造函数进行创建,否则我们使用指明的对象工厂来创建指定的对象.

浙公网安备 33010602011771号