How to create an instance of an annotation

前端 未结 8 1193
无人及你
无人及你 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:04

    I did this for adding annotation reference on my weld unit test:

    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ METHOD, FIELD, PARAMETER })
    public @interface AuthenticatedUser {
    
        String value() default "foo";
    
        @SuppressWarnings("all")
        static class Literal extends AnnotationLiteral implements AuthenticatedUser {
    
            private static final long serialVersionUID = 1L;
    
            public static final AuthenticatedUser INSTANCE = new Literal();
    
            private Literal() {
            }
    
            @Override
            public String value() {
                return "foo";
            }
        }
    }
    

    usage:

    Bean createUserInfo() {
        return MockBean.builder()
                .types(UserInfo.class)
                .qualifiers(AuthenticatedUser.Literal.INSTANCE)
                .create((o) -> new UserInfo())
                .build();
    }
    

提交回复
热议问题