java如何使用属性文件中的信息实例化类?
我有一个排序算法的项目,我需要使用属性文件来设置我将使用的算法,我的属性文件如下所示:
sorter=metodosOrdenamiento.QuickSorterImpl
其中“metodosOrdenamiento”是包,“QuickSorteImpl”是我的类。 我正在尝试这个:
public static Sorter getInstance() throws IllegalAccessException, InstantiationException {
Properties properties = new Properties();
Class<?> myClass = null;
try {
properties.load(new FileInputStream("java_3/MiFactory.properties"));
myClass = Class.forName(properties.get("sorter").toString());
} catch (IOException | ClassNotFoundException e) {
System.out.println("No se pudo obtener la clase");
e.printStackTrace();
}
assert myClass != null;
return (Sorter)myClass.newInstance();
}
但是它会生成一个“ClassNotFoundException”,这是从属性文件实例化类的正确方法吗
# 1 楼答案
您可以尝试使用以下代码
# 2 楼答案
根据@Elliott Frisch comment,您可能没有正确设置类路径,并且您使用的是不推荐的API
Class.newInstance()
。如果没有args构造函数,请使用Class.getConstructor().newInstance()
如果通过硬连接类来测试构造函数和类路径,那么调试就会容易得多:
如果可行,切换到从属性文件加载类名: