当我从class实例中获取方法并想要获取@override注释时。但是方法没有任何注释。获得@override 注解是不可能的吗?
代码如下。
package com.test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import javax.annotation.Resource;
public class ReflectionTest {
public static void main(String[] args) throws Exception {
ChildHoge childHoge = new ChildHoge();
Method method = childHoge.getClass().getMethod("init");
for (Annotation s : method.getAnnotations()) {
System.out.println(s);
}
Method method2 = childHoge.getClass().getMethod("a");
for (Annotation a : method2.getAnnotations()) {
System.out.println(a); // =>@javax.annotation.Resource(mappedName=, shareable=true, type=class java.lang.Object, authenticationType=CONTAINER, lookup=, description=, name=)
}
}
}
class SuperHoge {
public void init() {
}
}
class ChildHoge extends SuperHoge {
@Override
public void init() {
super.init();
}
@Resource
public void a() {
}
}
Run Code Online (Sandbox Code Playgroud)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
Run Code Online (Sandbox Code Playgroud)
它有RetentionPolicy.SOURCE哪些被编译器丢弃,这意味着它不能在运行时获得。您可以在JLS 9.6.4.2 中看到这一点。
如果注释 a 对应于类型 T,并且 T 具有对应于 的(元)注释 m
java.lang.annotation.Retention,则:
- 如果 m 有一个值为 的元素
java.lang.annotation.RetentionPolicy.SOURCE,那么 Java 编译器必须确保 a 不在出现 a 的类或接口的二进制表示中。
Javadoc forRetentionPolicy也描述了这一点:
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
372 次 |
| 最近记录: |