Use cases for implementing annotations

前端 未结 4 1832
半阙折子戏
半阙折子戏 2020-12-13 17:52

What are valid use cases for implementing annotations?

When designing primarily annotation based configuration systems I occasionally need to create classes which i

4条回答
  •  别那么骄傲
    2020-12-13 18:41

    I use it when I created an annotation and want to make its use optional, by providing a default when the annotation is omitted. This could occur when your library introduces a new annotation and you want your library to remain backwards compatible.

    In this example, BeanB is written in source code against an older version of your library, so you want to use a default when you identify such a class.

    @Id
    class BeanA {}
    
    // No annotation
    class BeanB {}
    

    The default implementation;

    private static final Id DEFAULT_ID = new Id() {
    
        @Override
        public IDType value() {
            return IDType.LOCAL;
        }
    
        @Override
        public Class annotationType() {
            return Id.class;
        }
    };
    

    Processing;

    Id beanId = (bean.getClass().isAnnotationPresent(Id.class))
        ? bean.getClass().getAnnotation(Id.class)
        : DEFAULT_ID;
    

提交回复
热议问题