【问题标题】:Create a hashmap with the names of the fields in the class as the key, and the values of those fields as the values of the map以类中的字段名称为键创建一个哈希映射,这些字段的值作为映射的值
【发布时间】:2022-08-23 22:58:52
【问题描述】:

假设您有一个类:SomeClass 的字段 a=10、b=20 和 c=30,其中 instanceOfSomeClass.getA()==10。我想要这样的地图

{
    a:10
    b:20
    c:30
}

我试过这个,但是让 Class can't access a member of class with modifiers \"private static final\",但我也不能修改这个类,使其没有 private static final:

      Field[] fields = SomeClass.class.getDeclaredFields();
      for (Field f : fields) {
        map.put(f.toString(), f.get(instanceOfSomeClass).toString());
      }

关于如何制作这个哈希图的任何想法?

  • 我有点困惑。 private static final 字段不是instanceOfSomeClass 相关联,那么您为什么要它们?
  • 我没有,我想是否可以在尝试检索字段之前检查一个字段是否为私有静态最终字段?

标签: java class reflection


【解决方案1】:

当您循环访问Field 对象时,使用Field.getModifiers() 来确定每个字段的可访问性(公共、私有、静态等)。

正如Field.getModifiers() 的JavaDoc 中所述,使用Modifier 类(具有isFinal()isPrivate() 等静态方法)来“解码”从getModifiers() 获得的int 值。

例如(未经测试的伪代码):

for (Field f : fields) {
    int modifiers = f.getModifiers();
    if (Modifier.isStatic(modifiers)) {  // Skip static fields, for example
        continue;
    }

    map.put(f.toString(), f.get(instanceOfSomeClass).toString());
}

【讨论】:

  • 并使用field.setAccessible(true) 覆盖访问限制。
  • 当你想跳过静态字段,而不是在第一次出现时终止循环,使用continue;而不是break;不是更有意义吗?我想f.toString() 应该是f.getName()...
  • 哎呀,很好,@Holger。固定的。至少我将其标记为“未经测试的伪代码”):-)
【解决方案2】:

我想这是您预期的解决方案:

import java.lang.reflect.*;
import java.util.*;

class SomeClass {
    public static int a = 10;
    public static int b = 20;
    public static int c = 40;
}

class HelloWorld {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<String, String>();
        try{
            SomeClass sc = new SomeClass();
            
            Field[] fields = SomeClass.class.getDeclaredFields();
        
            for(int i = 0; i < fields.length; i++) {

                // Getting the field's name and its value
                Object value = fields[i].get(sc);
                Object fieldName = fields[i].getName();

                // System.out.println("Field = " + fields[i].getName() + " Value = " + value + "\n");

                // Adding value into the HashMap
                map.put(fieldName.toString(), value.toString());
            }
            
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        // Iterating through the HashMap
        for (Map.Entry<String, String> e : map.entrySet()) {
            System.out.println("Key: " + e.getKey() + " Value: " + e.getValue());
        }
    }
}

输出

Key: a Value: 10
Key: b Value: 20
Key: c Value: 40

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 2018-07-29
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多