Java注释不起作用
我试图使用Java注释,但似乎无法让我的代码识别它的存在。 我做错了什么Java注释不起作用,java,annotations,Java,Annotations,我试图使用Java注释,但似乎无法让我的代码识别它的存在。 我做错了什么 import java.lang.reflect.*; import java.lang.annotation.*; @interface MyAnnotation{} public class FooTest { @MyAnnotation public void doFoo() { } public static void main(S
import java.lang.reflect.*;
import java.lang.annotation.*;
@interface MyAnnotation{}
public class FooTest
{
@MyAnnotation
public void doFoo()
{
}
public static void main(String[] args) throws Exception
{
Method method = FooTest.class.getMethod( "doFoo" );
Annotation[] annotations = method.getAnnotations();
for( Annotation annotation : method.getAnnotations() )
System.out.println( "Annotation: " + annotation );
}
}
您需要使用注释界面上的@Retention注释将注释指定为运行时注释 i、 e
简短回答:您需要将@Retention(RetentionPolicy.RUNTIME)添加到注释定义中 说明: 默认情况下,注释不是由编译器保存的。它们在运行时根本不存在。起初这听起来可能很傻,但是有很多注释只被编译器(@Override)或各种源代码分析器(@Documentation等)使用 如果您希望通过反射(如示例中所示)实际使用注释,则需要让Java知道您希望它在类文件本身中记录注释。那张纸条看起来像这样:
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation{}
有关更多信息,请查看官方文档,特别注意有关RetentionPolicy的部分。使用@Retention(RetentionPolicy.RUNTIME)
检查下面的代码。这对我很有用:
import java.lang.reflect.*;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation1{}
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{}
public class FooTest {
@MyAnnotation1
public void doFoo() {
}
@MyAnnotation2
public void doFooo() {
}
public static void main(String[] args) throws Exception {
Method method = FooTest.class.getMethod( "doFoo" );
for( Annotation annotation : method.getAnnotations() )
System.out.println( "Annotation: " + annotation );
method = FooTest.class.getMethod( "doFooo" );
for( Annotation annotation : method.getAnnotations() )
System.out.println( "Annotation: " + annotation );
}
}
您可能希望编辑代码以删除未使用的“annotations”局部变量,或者使用:for(Annotation:annotations){。。。
import java.lang.reflect.*;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation1{}
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{}
public class FooTest {
@MyAnnotation1
public void doFoo() {
}
@MyAnnotation2
public void doFooo() {
}
public static void main(String[] args) throws Exception {
Method method = FooTest.class.getMethod( "doFoo" );
for( Annotation annotation : method.getAnnotations() )
System.out.println( "Annotation: " + annotation );
method = FooTest.class.getMethod( "doFooo" );
for( Annotation annotation : method.getAnnotations() )
System.out.println( "Annotation: " + annotation );
}
}