是否可以将 Java 字符串转换为最终的 Java 对象。
举个例子:
在 .properties 文件中,我有以下语句
log_level=Level.ALL
现在,Level.ALL
是 Level 的最终对象。
我想要在代码中执行的操作是读取 .properties 文件,将 log_level 作为字符串读取,并 <somehow magically>
将字符串解析为对象 Level.ALL
.
最佳答案
仅存储“ALL”,然后使用Level.parse(stringFromConfig)
- 您将获得最终对象Level.ALL。
为了满足您对确切答案的渴望,我编写了以下代码。
我不完全确定这就是你的意思,但这是我能想到的最好的。
正如您在疯狂的catch
丛林中所看到的,我们正在处理的是危险的事情。
String str = "Level.SEVERE";
String pcg = Level.class.getPackage().getName();
str = pcg + "." + str;
// now we have package.ClassName.fieldName in "str"
String className = str.substring(0, str.lastIndexOf('.'));
String fieldName = str.substring(str.lastIndexOf('.') + 1, str.length());
try {
Class<?> c = Class.forName(className);
Field f = c.getDeclaredField(fieldName);
// here comes content of the field
// for non-final fields you must put field's class here instead of NULL
Object o = f.get(null);
System.out.println(o);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
关于Java:将字符串转换为现有的最终对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17996569/