2012-12-24 1 views
0

액세스 주석

class Parent extends MyBase { 
    @Annot(key="some.key", ref=Child.class) 
    public List<Child> children = new List<Child>(); 
} 

class Child extends MyBase { 
    @Annot(key="another.key") 
    public String id; 
} 

지금 내가이 말을 내가 클래스 아래 두 가지를 말

  • Parent 클래스 객체 =>parentchildren 3 개 Child 클래스의 객체를 포함
  • 명부.

즉, parent.children.get(0).id에 액세스 할 수 있습니다. 이제 키 배열 id의 키 시퀀스을 형성해야합니다. 여기 Key Sequencekey 값이 모두 연결 된 문자열이며 @Annot 주석입니다. 예를 들어,이 경우 키 순서는 some.key/another.key

는 자바 반사를 통해 수행하려면 어떤 방법입니까?

+0

키 시퀀스 란 무엇입니까? 비록 당신의 예제로도 나는 그것이 실제로 무엇인지 이해할 수 없다. – hoaz

+0

나는이 문제에 대한 더 나은 제목을 찾을 수 없었다. 그래서 누구나 가장 좋은 제목을 주려고 환영합니다. – Samiron

+0

'@ Annot' 어노테이션의'key' 값의 시퀀스 – Samiron

답변

0

children의 개체를 사용하지 않는 방법 일 수 있습니다. 그것은 일반적인 유형의 어린이를 검사하고 주석을 찾기 위해이 클래스를 검사합니다.

Field childrenField = Parent.class.getField("children"); 
    Annotation[] annotations = childrenField.getDeclaredAnnotations(); 

    String key = null; 
    for (Annotation annotation : annotations) { 
     if (annotation instanceof Annot) { 
      Annot a = (Annot) annotation; 
      key = a.key(); 
      break; 
     } 
    } 

    ParameterizedType type = (ParameterizedType) childrenField.getGenericType(); 
    Class<?> c = (Class<?>) type.getActualTypeArguments()[0]; 
    annotations = c.getDeclaredField("id").getAnnotations(); 
    for (Annotation annotation : annotations) { 
     if (annotation instanceof Annot) { 
      Annot a = (Annot) annotation; 
      key += "/" + a.key(); 
      break; 
     } 
    } 

    System.out.println(key); 

주석에 대한 자세한 내용은 this guide를 참조하십시오.

+0

유망한 사운드 ... 나는 당신의 솔루션을 완전히 동화시키기 위해 약간의 시간이 필요합니다. 나는 분명히 회신을 가지고 돌아올 것이다. – Samiron

관련 문제