2013-05-06 2 views
0

리플렉션을 사용하여 해당 해시 맵을로드하려고합니다. 그러나 필드를 찾을 예외가 없습니다. 문제가 무엇이라고 생각하는지 알려주세요. 감사합니다리플렉션 Java를 사용하여 해시 맵 가져 오기, 코드 오류

//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) 
+0

'무엇을 포함 mapName'는 무엇입니까? 이 메소드 호출로'Field.class.getField (mapName);'클래스'Field'에있는'mapName'이라는 필드를 얻으려고합니다. 그것은 거의 당신이 원하는 것이 아닙니다. –

+0

스택 추적주세요! – christopher

+0

지도가 비공개입니까? 대신에,'getDeclaredField'를 사용할 필요가있는 경우, 그것을 조작 할 수 있도록 (듯이)'setAccessible = true'를 사용할 필요가 있습니다. –

답변

4

당신은 전화, 당신은 당신이에지도가 무엇이든 클래스 사용할 Field.class.getField(mapName);

을 원하지 않는 'MyClass에'

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

편집 : 필드가 private이므로 getField (..)에서 getDeclaredField (...)로 변경되었습니다.

+0

개인용 인 경우 얻을 수 없다는 것에 대한 세부 정보를 추가 할 수 있습니다 –

+0

시도했으나 작동하지 않습니다. MatchingGraph.class.getField (mapName) 및 여전히 오류 –

+0

동일한 오류가 발생 했습니까? 새 스택 추적을 게시하십시오 ... – rolfl