Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get field value in Java reflection [duplicate]

I have following field in a class:

private String str = "xyz";

How do I get the value xyz using the field name only i.e.

I know the name of the field is str and then get the assigned value. Something like:

this.getClass().getDeclaredField("str").getValue();

Currently the Reflection API has field.get(object).

like image 674
Saikat Avatar asked Nov 04 '25 08:11

Saikat


2 Answers

You can use:

String value = (String) this.getClass().getDeclaredField("str").get(this);

Or in a more generalized and safer form:

Field field = anObject.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
String value = (String) field.get(anObject);

And for your example, this should be enough:

String value = this.str; 

But you probably know of that one.

Note: anObject.getClass().getDeclaredField() is potentially unsafe as anObject.getClass() will return the actual class of anObject. See this example:

Object anObject = "Some string";
Class<?> clazz = anObject.getClass();
System.out.println(clazz);

Will print:

class java.lang.String

And not:

class java.lang.Object

So for your code's safety (and to avoid nasty errors when your code grows), you should use the actual class of the object you're trying to extract the field from:

Field field = YourObject.class.getDeclaredField(fieldName);
like image 84
Lino Avatar answered Nov 06 '25 00:11

Lino


Imagine you have object in variable foo.

Then you need to get Field

Field field = foo.getClass().getDeclaredField("str");

then allow access to private field by:

field.setAccessible(true);

and you can have value by:

Object value = field.get(foo);
like image 20
talex Avatar answered Nov 06 '25 00:11

talex