網上沒找到相關資料,自己嘗試做了下。
註解1
@Target({ElementType.METHOD,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Test1 {
String test1v() default "測試1的值";
}
註解2使用註解1
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Test1
public @interface Test2 {
String test2v() default "測試2的值";
}
方法使用註解2
class TestClass{
@Test2
public void testMethod(){
}
}
嘗試獲取
@Test
void main() throws NoSuchMethodException {
// 1.直接從Test2的class獲取Test1
Test1 test1FromTest2 = Test2.class.getAnnotation(Test1.class);
// 正常輸出
System.out.println(test1FromTest2.test1v());
// 2.拿到testMethod方法上的test2註解,然後再拿到test2註解上的test1註解
Test2 test2 = TestClass.class.getDeclaredMethod("testMethod", null).getAnnotation(Test2.class);
// debug發現這個是個代理對象,因此實際上@Test1註解已經被丟棄了
Class<? extends Test2> test2Class = test2.getClass();
// Test1 空指針
Test1 test1FromTest2ByMethon = test2Class.getAnnotation(Test1.class);
System.out.println(test1FromTest2ByMethon.test1v());
}
獲取失敗,debug發現從方法上獲取的Test2類的class對象是代理對象,而代理對象本身並沒有拿到該註解。
網上說使用getSuperClass獲取到代理的原始對象,但是這個代理使用的不是繼承,一番查找後,使用如下方法獲取代理的原始對象
private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
h.setAccessible(true);
return h.get(proxy);
}
但是拿到的,並非原始代理,而是AnnotationInvocationHandler
不過他的類型裏面有我們想要的Test2註解,但是暫時沒想到辦法獲取。
目前似乎只能直接通過Test2拿到Test1中的值,不能通過方法拿到Test2再拿到Test1,