Reflection : returning wrong fields

2019-08-05 16:52发布

问题:

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 :

  1. serialVersionUID
  2. 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?

回答1:

You should replace objClass.getClass().getDeclaredFields() with objClass.getDeclaredFields()

objClass is the class object of MyClass

objClass.getClass() is the class object of java.lang.Class

You were getting the declared fields in the class java.lang.Class in your code