Reputation: 405
I want to get the value a class attribute, But I am getting exception : java.lang.NoSuchFieldException
Person.class
public class Person {
public static final String name = "person name";
}
MainActivity.class
...
private void method() {
Class myClass = Person.class;
String name = myClass.getField("name");
}
...
I am getting a java.lang.NoSuchFieldException exception for the getField method.
I tried these solutions but with no avail ...
Change getField method to getDeclaredField
Surround the code by try/catch, and got another error (Incompatible types : java.lang.String and java.lang.reflect.Field)
Invalidate Android Studio caches and restart
I don't Know how to access this value, Any solutions or suggestions are welcomed.
Thanks in advance.
Upvotes: 1
Views: 2877
Reputation:
It's a static constant. Static means there is only one value at a time possible. Or say it like this: The class attribute 'name' is a class attribute, not an object attribute! The attribute belongs to the class!
So you don't need to create an instance of your Person class.
You just can use:
String name = Person.name;
Remember: this only works cause the name belongs to the class. And it does so, because you declared your name variable static.
Upvotes: 0
Reputation: 483
try{
Class _person = Person.class;
Field field = _person.getField("name");
Object value = field.get(null);
String valueString = (String)value; /*The String you are looking for*/
}catch (Exception e) {
//TODO handle exception
}
String valueString = Person.name /*The value you are looking for*/
Person _person = new Person();
String personName = _person.name;
Upvotes: 1
Reputation: 2283
If you want to access the value of the field, you can use the get(...)
method with a null argument - since it's a static field, it does not require any instance:
private void method() {
Class myClass = Person.class;
Field field = myClass.getField("name");
String name = field.get(null);
Log.d("Test", "field value: " + name);
}
In your case, it doesn't matter whether you use getField(...)
or getDeclaredField(...)
. You would want to use the latter if you want to grab a field in its superclass or an interface implemented by your class.
For example, if Person
were to extend from a class that has a field named sample
, you would need to use getDeclaredField("sample")
instead.
Upvotes: 1
Reputation: 51
Since that's a constant you declared, access it directly with the class name as below,
String name = Person.name;
Upvotes: 0
Reputation: 18610
Change getField method to getDeclaredField
Surround the code by try/catch, and got another error (Incompatible types : java.lang.String and java.lang.reflect.Field)
that because getDeclaredField
will return object of type Field
not String
,
just change your code to this
Field field = myClass.getDeclaredField("name");
//do something with field
Upvotes: 1