[英]How to parse a Field object to a String (Java)
I have a Field object Field f
and know that it is an instance of String
. 我有一个Field对象Field f
并且知道它是String
一个实例。
How do I actually parse this Field f
to a String s
? 我实际上如何将此Field f
解析为String s
?
I tried to set the value of the field (this doesn't work). 我试图设置字段的值(这不起作用)。
My Code: 我的代码:
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();
}
}
}
A field is never an instance of a String. 字段永远不会是字符串的实例。 It's a field. 这是一个领域。 What you probably think is, that the Field stores a String. 您可能会想到,该字段存储一个字符串。 And you do not parse fields, you can only access them. 而且您不解析字段,只能访问它们。 A field belongs to a class, and thus, to get/set it, you must give the actual object where you want to get the value from (or set it to) as a parameter (except for static fields, see below). 字段属于一个类,因此,要获取/设置它,必须将要从中获取值(或将其设置为)的实际对象作为参数(静态字段除外,请参见下文)。
A field can either be static or not. 字段可以是静态的,也可以不是。 For example... 例如...
class Something {
private static String myField; // static
private String myOtherField; // not static
}
If it is static, then you do not need an object to access it and would call... 如果它是静态的,则您不需要对象即可访问它,并且会调用...
field.setAccessible(true); // to allow accessing it if private, etc.
String s = (String)field.get(null);
If the field is not static, then you need an object in which the field has some value, for example something like this... 如果该字段不是静态的,那么您需要一个对象,其中该字段具有一定的值,例如这样的值...
Something mySomething = new Something();
something.setMyOtherField( "xyz" );
...and you would end up calling... ...您最终会打电话给...
field.setAccessible(true); // to allow accessing it if private, etc.
String s = (String)field.get( something ); // s == "xyz"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.