如何创建注解的实例 [英] How to create an instance of an annotation

查看:28
本文介绍了如何创建注解的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些 Java 注释魔法.我必须说我仍然在追赶注释技巧,某些事情对我来说仍然不是很清楚.

I am trying to do some Java annotation magic. I must say I am still catching up on annotation tricks and that certain things are still not quite clear to me.

所以...我有一些带注释的类、方法和字段.我有一个方法,它使用反射对类运行一些检查并将一些值注入到类中.这一切正常.

So... I have some annotated classes, methods and fields. I have a method, which uses reflection to run some checks on the classes and inject some values into a class. This all works fine.

但是,我现在面临一个需要一个注释实例(可以这么说)的情况.所以......注释不像常规接口,你不能对类进行匿名实现.我得到它.我已经浏览了一些关于类似问题的帖子,但我似乎无法找到我正在寻找的答案.

However, I am now facing a case where I need an instance (so to say) of an annotation. So... annotations aren't like regular interfaces and you can't do an anonymous implementation of a class. I get it. I have looked around some posts here regarding similar problems, but I can't seem to be able to find the answer to what I am looking for.

我基本上想获取注释的实例,并能够使用反射设置其中的一些字段(我想).有没有办法做到这一点?

I would basically like to get and instance of an annotation and be able to set some of it's fields using reflection (I suppose). Is there at all a way to do this?

推荐答案

嗯,显然没有那么复杂.真的!

Well, it's apparently nothing all that complicated. Really!

正如一位同事所指出的,您可以像这样简单地创建注释的匿名实例(就像任何接口一样):

As pointed out by a colleague, you can simply create an anonymous instance of the annotation (like any interface) like this:

我的注释:

public @interface MyAnnotation
{

    String foo();

}

调用代码:

class MyApp
{
    MyAnnotation getInstanceOfAnnotation(final String foo)
    {
        MyAnnotation annotation = new MyAnnotation()
        {
            @Override
            public String foo()
            {
                return foo;
            }

            @Override
            public Class<? extends Annotation> annotationType()
            {
                return MyAnnotation.class;
            }
        };

        return annotation;
    }
}

感谢 Martin Grigorov.

这篇关于如何创建注解的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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