我有一个 Field 对象 Field f
并且知道它是 String
的实例。
如何实际将此 Field f
解析为 String s
?
我尝试设置该字段的值(这不起作用)。
我的代码:
Field[] fields=LanguageHandler.class.getDeclaredFields();
for(Field field:fields){
if(field.getType().equals(String.class)){
field.setAccessible(true);
try {
field.set(handler, ChatColor.translateAlternateColorCodes('&', cfg.getString(field.getName())));
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最佳答案
字段永远不是字符串的实例。这是一个领域。您可能会认为 Field 存储的是字符串。并且您不能解析字段,只能访问它们。字段属于一个类,因此,要获取/设置它,您必须给出要从中获取值(或将其设置为)的实际对象作为参数(静态字段除外,请参见下文)。
字段可以是静态的,也可以不是静态的。例如...
class Something {
private static String myField; // static
private String myOtherField; // not static
}
如果它是静态的,那么您不需要对象来访问它并调用...
field.setAccessible(true); // to allow accessing it if private, etc.
String s = (String)field.get(null);
如果该字段不是静态的,那么您需要一个该字段具有某些值的对象,例如这样的...
Something mySomething = new Something();
something.setMyOtherField( "xyz" );
...你最终会打电话...
field.setAccessible(true); // to allow accessing it if private, etc.
String s = (String)field.get( something ); // s == "xyz"
关于java - 如何将 Field 对象解析为 String (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32024766/