注释不可见? [英] annotation invisible?

查看:37
本文介绍了注释不可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我很困惑.我有一个带有自定义注释的类,我似乎无法验证该注释是否存在.我在这里做错了什么?如果我运行 MyOperationTest(见下文),结果如下:

This puzzles me. I have a class with a custom annotation and I can't seem to verify that the annotation is present. What am I doing wrong here? If I run MyOperationTest (see below), I get this as a result:

implements Library.Operation: true
has @Library.Marker: false
Tada!

<小时>

库.java:


Library.java:

package com.example.gotchas;

public class Library {
    private Library() {}

    public @interface Marker {}

    public interface Operation {
        public void execute(); 
    }
}

MyOperation.java:

MyOperation.java:

package com.example.gotchas;

@Library.Marker
public class MyOperation implements Library.Operation {
    @Override public void execute() {
        System.out.println("Tada!");
    }
}

MyOperationTest.java:

MyOperationTest.java:

package com.example.gotchas;

public class MyOperationTest {
    static public void main(String[] args)
    {
        try {
            Class<?> cl = Class.forName("com.example.gotchas.MyOperation");
            boolean implementsLibraryOperation =
                Library.Operation.class.isAssignableFrom(cl);
            boolean hasLibraryMarker =
                cl.isAnnotationPresent(Library.Marker.class);
            System.out.println("implements Library.Operation: "
                    +implementsLibraryOperation);
            System.out.println("has @Library.Marker: "+hasLibraryMarker);
            if (implementsLibraryOperation)
            {
                Class<? extends Library.Operation> opClass = 
                    cl.asSubclass(Library.Operation.class); 
                Library.Operation op = opClass.newInstance();
                op.execute();
            }
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (InstantiationException e) {
            e.printStackTrace();
        }
        catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

推荐答案

你必须定义 @Retention 用于您的注释:

You have to define @Retention for your annotation:

@Retention(RetentionPolicy.RUNTIME)
public @interface Marker {}

否则在运行时不会保留注解.

Otherwise the annotation is not retained at runtime.

(如果你想限制你的注解只在类上使用,你也可以添加显式的@Target(ElementType.TYPE))

(You can also add explicit @Target(ElementType.TYPE) if you want to limit the usage of your annotation only on classes)

作为旁注 - 将注释定义为内部类并不是一种常见的做法.

As a sidenote - it is not a common practice to define annotations as inner classes.

这篇关于注释不可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆