Java Can';无法从方法中获取@override注释
当我从Java Can';无法从方法中获取@override注释,java,annotations,Java,Annotations,当我从类实例中获取方法,并希望获取@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(St
类
实例中获取方法,并希望获取@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() {
}
}
它有RetentionPolicy.SOURCE
,编译器会将其丢弃,这意味着无法在运行时获取它。您可以在中看到这一点
如果注释a对应于类型T,且T具有
(元)注释m,对应于
java.lang.annotation.Retention
,然后:
- 如果m有一个值为
java.lang.annotation.RetentionPolicy.SOURCE
,则java编译器必须
确保类的二进制表示形式中不存在
或在其中显示的界面
而RetentionPolicy
的Javadoc也描述了这一点:
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
...
它有RetentionPolicy.SOURCE
,编译器会将其丢弃,这意味着无法在运行时获取它。您可以在中看到这一点
如果注释a对应于类型T,且T具有
(元)注释m,对应于
java.lang.annotation.Retention
,然后:
- 如果m有一个值为
java.lang.annotation.RetentionPolicy.SOURCE
,则java编译器必须
确保类的二进制表示形式中不存在
或在其中显示的界面
而RetentionPolicy
的Javadoc也描述了这一点:
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
...
您可以使用反射API检查该方法是否被重写
e、 g
如果返回的类是您自己的,则不会重写它;如果是其他内容,则该子类已重写它。您可以使用反射API检查该方法是否被重写
e、 g
如果返回的类是您自己的,则不会重写它;如果是其他内容,则该子类已覆盖它。So:No。它无法从类文件中获取。So:No。它无法从类文件中获取。
class.getMethod("myMethod").getDeclaringClass();