Reflection : returning wrong fields

余生长醉 提交于 2019-12-24 16:13:02

问题


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



来源:https://stackoverflow.com/questions/32644369/reflection-returning-wrong-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!