24

I have a method:

public void extractStringFromField(Class<?> classToInspect) {
    Field[] allFields = classToInspect.getDeclaredFields();

    for(Field field : allFields) {
        if(field.getType().isAssignableFrom(String.class)) {
            System.out.println("Field name: " + field.getName());

            // How to get the actual value of the string?!?!
            // String strValue = ???
        }
    }
}

When this runs I get output like:

Field name: java.lang.String

Now how do I extract the actual string value into strValue, using reflection?

5
  • Shouldn't it be? System.out.println("Field name: " + field.getName()); Commented Jul 4, 2013 at 3:40
  • Yes - cut n' paste error! Commented Jul 4, 2013 at 3:42
  • 1
    You want to get the value of which field? On which object? Commented Jul 4, 2013 at 3:47
  • If classToInspect is a Widget, and the Widget class has a String field called fizz, and the value of that Widget#fizz instance is "buzz", then I want to get the buzz string into an actual String instance. Commented Jul 4, 2013 at 3:50
  • 1
    @TicketMonster A field only makes sense either as a static field of a Class or as an instance field. You therefore have to specify which instance it is (or null when it's static) with the Field#get(Object) method. Internally, it looks like Object.Field to retrieve the value. Commented Jul 4, 2013 at 4:06

5 Answers 5

38

It looks like you need a reference to an instance of the class. You would want to call get and pass in the reference, casting the return to a String.

You can use get as follows:

String strValue = (String) field.get (objectReference);
Sign up to request clarification or add additional context in comments.

4 Comments

It's an unfortunate aspect of the API that you need to pass in a reference even if the field is static.
It also may be worth noting that you might need to make sure that the field is accessible like so: field.setAccessible(true);
I tried passing null and got a NullPointerException in Java 1.7.0_79
answering to @th3morg : it works if you pass an instance ( new Foo() ) instead of null
8

In ideal situations,Class does not hold data. It merely holds the information about the structure and behavior of its instances and Instances of the Classes hold your data to use. So your extractStringFromField method can not extract values unless you pass any instances (from where it will actually extract values).

If the name of the parameter of the reference, you are passing to extract value is instance, then you can easily get what you want like bellow:

String strValue = (String)field.get(instance);

Comments

2

Just usefull example code for reflection fields:

Field[] fields = InsanceName.getDeclaredFields();
for (Field field : fields) {      //array for fields names

System.out.println("Fields: " + Modifier.toString(field.getModifiers())); // modyfiers
System.out.println("Fields: " + field.getType().getName());  //type var name
System.out.println("Fields: " + field.getName());        //real var name
field.setAccessible(true);                                //var readable
System.out.println("Fields: " + field.get(InsanceName));  //get var values  
System.out.println("Fields: " + field.toString());     //get "String" values
System.out.println("");  //some space for readable code
}

Comments

1

Just had the same issue. This Thread somewhat helped. Just for reference if somebody else stumbles upon this thread. I used the StringBuilder class to convert so basically:

StringBuilder builder = new StringBuilder();
builder.append(field.get(object))

Which has multiple advantages. One that you do not explicitly cast (which btw. causes problems with primitive types int vs. Integer) but also of being more efficient if you have multiple string operations sequentialy. In time critical code parts.

Comments

0
String strValue = field.getName().toString();

Full code looks like this:

public static void extractStringFromField(Class<?> Login) {
    Field[] allFields = Login.getDeclaredFields();

    for(Field field : allFields) {
        String strValue = field.getName().toString();
//          if(field.getType().isAssignableFrom(String.class)) {
            System.out.println("Field name: " + strValue);
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.