I was trying to use reflection API to get the fields of a class, I was doing it by passing the the class as an argument to the following method
private void someMethod(Class<?> objClass) throws IOException {
String className= objClass.getSimpleName();
Map<String, String> fieldsAndDataType = new LinkedHashMap<>();
for (Field field : objClass.getClass().getDeclaredFields())
{
String fieldName = field.getName();
String fieldDataType = field.getType().toString();
fieldsAndDataType.put(fieldName, fieldDataType);
}
Log.d("here","here "+fieldsAndDataType);
}
I am calling the method like
someMethod(MyClass.class);
But instead of returning me the fields of 'MyClass', The fields which I am getting are :
- serialVersionUID
- name
But my class is a simple class with three properties and having primitive dataTypes with some getters and setters only.However the
String className= objClass.getSimpleName();
is returning me correct class name.
The someMethod()
is not giving me the member variables of my class.
How can I get them?
You should replace
objClass.getClass().getDeclaredFields()
withobjClass.getDeclaredFields()
objClass
is the class object ofMyClass
objClass.getClass()
is the class object ofjava.lang.Class
You were getting the declared fields in the class
java.lang.Class
in your code