使用反射Java获取hashmap,代码错误

使用反射Java获取hashmap,代码错误,java,reflection,Java,Reflection,我正在尝试使用反射加载相应的hashmap。然而,我得到一个字段未找到异常。请让我知道你认为问题是什么。谢谢 //Find the map HashMap<String, Matches> map = null; //Reflection to find the appropriate map try { Field field = Field.class.getField(mapName); //except

我正在尝试使用反射加载相应的hashmap。然而,我得到一个字段未找到异常。请让我知道你认为问题是什么。谢谢

//Find the map
        HashMap<String, Matches> map = null;

        //Reflection to find the appropriate map
        try {
            Field field = Field.class.getField(mapName); //exception (mapname = lookupHashmap) this class has a lookupHashmap declared)
            try {

                //Set the map
                map = (HashMap<String, Matches>)field.get(this); //Not sure if this is correct

            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

您不需要
Field.class.getField(mapName)

你想使用地图上的任何类,称它为“MyClass”

Field field = MyClass.class.getDeclaredField(mapName);

编辑:从getField(…)更改为getDeclaredField(…),因为该字段是私有的。

您不需要
field.class.getField(mapName)

你想使用地图上的任何类,称它为“MyClass”

Field field = MyClass.class.getDeclaredField(mapName);

编辑:从getField(…)更改为getDeclaredField(…),因为该字段是私有的。

@Rolfl解决了您的问题

我建议

并使用该方法

BeanUtils.copyProperties(source, target);

@Rolfl解决了你的问题,我想

我建议

并使用该方法

BeanUtils.copyProperties(source, target);

地图名包含什么?您正试图通过此方法调用
field.class.getField(mapName),从类
field
中获取名为
mapName
的字段。这几乎肯定不是你想要的。你的地图是私人的吗?如果是,则需要使用
getDeclaredField
,并且需要使用
setAccessible=true
才能对其进行操作。地图是公共的。此类(称为Matcher)声明了一个名为lookupMap的hashmap。@请参阅rolfl的答案。您需要类的class对象而不是
字段。class
堆栈跟踪只显示NoSuchFieldException(在Field=Field.class.getField(mapName)处调用);
mapName
包含什么?您正试图通过此方法调用
field.class.getField(mapName),从类
field
中获取名为
mapName
的字段
。这几乎肯定不是你想要的。你的地图是私有的吗?如果是私有的,你需要使用
getDeclaredField
,你需要使用
setAccessible=true
来操作它。地图是公共的。这个类(称为Matcher)声明了一个名为lookupMap的hashmap。@请看rolfl的答案。您需要的类对象不是
字段。class
堆栈跟踪只显示NoSuchFieldException(在Field=Field.class.getField(mapName)处调用);可能希望添加有关无法获取它(如果它是私有的)的详细信息。已尝试,不起作用。已更改为MatchingGraph.class.getField(mapName),但仍然error@rolfl该字段可能是私有的。需要
getDeclaredField()
可能需要添加有关无法获取它(如果它是私有的)的详细信息。已尝试,但不起作用。更改为MatchingGraph.class.getField(mapName),但仍然无效error@rolfl该字段可能是私有的。需要
getDeclaredField()