0

是否可以将 Java 字符串转换为最终的 Java 对象。

举个例子:

在 .properties 文件中,我有以下语句

log_level=Level.ALL

现在,Level.ALL是 Level 的最终对象。

我想要在代码中做的是读取 .properties 文件,将 log_level 作为 String 读取并将 String<somehow magically>解析为 object Level.ALL

4

2 回答 2

2

仅存储“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();
}
于 2013-08-01T14:18:59.197 回答
0
if (System.getProperty("STANDALONE_LOG_LEVEL")!=null){
                    String logLevel= System.getProperty("STANDALONE_LOG_LEVEL");
                    switch(logLevel){

                    case "ERROR" :  this.aRootLogLevel=Level.ERROR;
                                    break;
                    case "DEBUG" :  this.aRootLogLevel=Level.DEBUG;
                                    break;
                    case "INFO" :   this.aRootLogLevel=Level.INFO;
                                    break;
                    case "WARN" :   this.aRootLogLevel=Level.WARN;
                                    break;
                    case "FATAL" :  this.aRootLogLevel=Level.FATAL;
                                    break;
                    default :       this.aRootLogLevel=Level.INFO;
                   }
            }
 rootLogger.setLevel( this.aRootLogLevel );
于 2017-03-01T09:50:32.940 回答