How to create custom annotation in java?

后端 未结 3 1151
难免孤独
难免孤独 2021-02-01 23:28

I want to create custom annotation in java for DirtyChecking. Like I want to compare two string values using this annotation and after comparing it will return a

3条回答
  •  天涯浪人
    2021-02-02 00:07

    First you need to mark if annotation is for class, field or method. Let's say it is for method: so you write this in your annotation definition:

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface DirtyCheck {
        String newValue();
        String oldValue();
    }
    

    Next you have to write let's say DirtyChecker class which will use reflection to check if method has annotation and do some job for example say if oldValue and newValue are equal:

    final class DirtyChecker {
    
        public boolean process(Object instance) {
            Class clazz = instance.getClass();
            for (Method m : clazz.getDeclaredMethods()) {
                if (m.isAnnotationPresent(DirtyCheck.class)) {
                    DirtyCheck annotation = m.getAnnotation(DirtyCheck.class);
                    String newVal = annotation.newValue();
                    String oldVal = annotation.oldValue();
                    return newVal.equals(oldVal);
                }
            }
            return false;
        }
    }
    

    Cheers, Michal

提交回复
热议问题