简体   繁体   中英

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 .

How do I actually parse this Field f to a 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM