如何将 Field 对象解析为字符串 (Java)
How to parse a Field object to a String (Java)
我有一个 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,因此,对于 get/set 它,您必须将要从中获取值(或将其设置为)的实际对象作为参数(静态字段除外,见下文)。
字段可以是静态的,也可以不是。例如...
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"
我有一个 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,因此,对于 get/set 它,您必须将要从中获取值(或将其设置为)的实际对象作为参数(静态字段除外,见下文)。
字段可以是静态的,也可以不是。例如...
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"