反思:返回错误的字段 [英] Reflection : returning wrong fields

查看:21
本文介绍了反思:返回错误的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用反射 API 来获取类的字段,我是通过将类作为参数传递给以下方法来实现的

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);

    }

我正在调用像

someMethod(MyClass.class);

但是我没有返回MyClass"的字段,我得到的字段是:

But instead of returning me the fields of 'MyClass', The fields which I am getting are :

  1. serialVersionUID
  2. 姓名

但我的类是一个简单的类,具有三个属性,并且只有一些 getter 和 setter 的原始数据类型.但是

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();

String className= objClass.getSimpleName();

正在返回正确的班级名称.

is returning me correct class name.

someMethod() 没有给我我的类的成员变量.我怎样才能得到它们?

The someMethod() is not giving me the member variables of my class. How can I get them?

推荐答案

您应该将 objClass.getClass().getDeclaredFields() 替换为 objClass.getDeclaredFields()

objClassMyClass

objClass.getClass()java.lang.Class

您在代码中获得了 java.lang.Class 类中声明的字段

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

这篇关于反思:返回错误的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆