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).
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With