Freakey
Freakey

Reputation: 85

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();
     }
   }
}

Upvotes: 1

Views: 1707

Answers (1)

Florian Schaetz
Florian Schaetz

Reputation: 10652

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"

Upvotes: 2

Related Questions