我正在尝试使用反射加载相应的 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();
}
堆栈跟踪
java.lang.NoSuchFieldException: majorFieldLookup
at java.lang.Class.getField(Class.java:1522)
at MatchingGraph.getResultsForMap(MatchingGraph.java:245)
at MatchingGraph.getmajorFieldMatches(MatchingGraph.java:196)
at Matcher.findMatches(Matcher.java:95)
at Tester.main(Tester.java:27)
最佳答案
您不需要Field.class.getField(mapName);
您想使用 map 所在的任何类,请将其命名为“MyClass”
Field field = MyClass.class.getDeclaredField(mapName);
编辑:从 getField(..) 更改为 getDeclaredField(...),因为该字段是私有(private)的。
关于java - 使用反射Java获取hashmap,代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16402416/