How to create an instance of an annotation

前端 未结 8 1202
无人及你
无人及你 2021-01-30 12:47

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 hav

8条回答
  •  心在旅途
    2021-01-30 13:20

    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:

    MyAnnotation:

    public @interface MyAnnotation
    {
    
        String foo();
    
    }
    

    Invoking code:

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

    Credits to Martin Grigorov.

提交回复
热议问题