를 통해 자바 주석에 대한 정보를 얻기 나는이 주석 형 클래스가 있습니다반사
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface RemoteTcpAccess {
public int port();
}
와 같은 다른 클래스에 적용 :
@RemoteTcpAccess(port = 444)
public class CalculatorService {
public int Add(int a, int b) {
return a + b;
}
public void DisplayText(String text) {
System.out.println(text);
}
}
지금 나는 CalculatorService 클래스 객체를 얻고 시도 RemoteTcpAccess 주석에 대한 정보를 얻으려면 :
private static void CheckRemoteTcpAccess(List<Class> classes) {
for (Class class1 : classes) {
for (Annotation annotation : class1.getDeclaredAnnotations()) {
if (AnnotationEquals(annotation, ComponentsProtocol.REMOTE_TCP_ACCESS)) {
//GET INFORMATION
}
}
}
}
private static boolean AnnotationEquals(Annotation classAnnotation, String protocolAnnotation) {
return classAnnotation.toString()
.substring(0, classAnnotation.toString().indexOf("("))
.equals(protocolAnnotation);
}
나는 인식 할 수있다. 클래스가에 RemoteTcpAccess 주석을 적용했다,하지만 난 주석을 가지고 있으며, 어떤 필드에 대한 inforamtion를 얻을하지 못할 경우처럼 해당 필드, 무슨 값 :
필드 포트 - 값을 444
어떻게 얻을 방법이 있나요 반사를 통해 그 inforamtion?
감사
매우 유용합니다, 나는 instanceof 키워드를 확인합니다! 하지만 항상 instanceof RemoteTcpAccess 아니에요? –
@ JohnSmith이 예에서는 네,하지만 상황을 생각해보십시오 (특수 효과를 통해 반복). 클래스에 여러 개의 주석이있는 경우 'RemoteTcpAccess' 유형이 아닐 수도 있습니다. 맹목적으로 캐스팅을 수행하고 나중에 클래스가 주석을 얻으면 코드가 중단됩니다. –