獲取有關在Java中的註釋信息,我有這樣的註釋類型類:通過反射
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
有什麼辦法如何獲得那些通過反思的信息?
感謝
非常有用,我會檢查instanceof關鍵字!但不是永遠instanceof RemoteTcpAccess嗎? –
@JohnSmith在這個例子中是的,但想想你的情況(通過註釋循環)。如果該類有多個註釋,則它們可能不是「RemoteTcpAccess」類型。如果您盲目地執行投射並且稍後課程獲得註解,則代碼將會中斷。 –