java - 在运行时初始化实例
问题描述
我使用工厂模式在运行时初始化一个新实例。
问题:哪个版本最快?Java 12 是否有更好的模式或解决方案?
/**
* VERSION 1:
*
* Uses Reflection with clazz
*
* @param <T>
* @param colorClass
* @return instance type of derived colorClass
*/
public <T extends Color> T createInstance(Class<T> colorClass) {
T t = null;
try {
t = colorClass.getConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
* VERSION 2:
*
* Uses Reflection with canonical name of class
*
* @param <T>
* @param colorClass
* @return instance type of derived colorClass
*/
public <T extends Color> T createInstance(String colorClassName) {
T red = null;
try {
red = (Color) Class.forName(colorClassName).getConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return red;
}
/**
* VERSION 3: (abstract factory pattern?)
*
* Uses switch without reflection
*
* @param <T>
* @param colorClass
* @return instance type of derived colorClass
*/
public <T extends Color> T createInstance(ColorName colorName) {
T t = null;
switch (colorName) {
case red:
return new Red();
break;
case green:
return new Green();
break;
case blue:
return new Blue();
break;
case black:
return new Black();
break;
default:
break;
}
return t;
}
正如建议的那样,我包括了第 4 版(这似乎是最好的解决方案!):
public enum ColorName {
Red(ColorRed.class),
Green(ColorGreen.class),
Blue(ColorBlue.class),
Black(ColorBlack.class);
ColorName(Class<?> clazz) {
this.clazz = clazz;
}
private final Class<?> clazz;
public Class<?> getClazz() {
return clazz;
}
public Color createColor() {
Color c = null;
try {
c = (Color) this.clazz.getConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
}
解决方案
推荐阅读
- java - 如何在java sql中插入表?以及如何解决 http 500 错误
- c# - “无法在 DLL“xy”中找到名为“connect2”的入口点
- python-3.x - 如何将多种类型的数据帧写入 hdf5 文件中的表?
- sql - 评估一个字符串是否“几乎”匹配另一个
- javascript - 当 REST api 返回错误状态时渲染不同的组件
- react-native - npm 不运行 postinstall
- elasticsearch - Elasticsearch 限制搜索结果中的某些字段
- python - AttributeError:“RandomForestRegressor”对象没有属性“估计器”
- c++ - 调试代码中的溢出问题问题
- angular-cli - 如何在 Angular cli 中查看当前的 webpack 配置?