如何在java中创建自定义注释?

我想在Java中为DirtyChecking创建自定义注释。 就像我想使用此注释比较两个字符串值,并在比较后将返回一个boolean值。

例如:我将@DirtyCheck("newValue","oldValue")放在属性上。

假设我创建了一个界面:

  public @interface DirtyCheck { String newValue(); String oldValue(); } 

我的问题是

  1. 我在哪里创建一个类来创建一个比较两个字符串值的方法? 我的意思是,这个注释如何通知我必须调用这个方法?
  2. 如何检索此方法的返回值?

首先,您需要标记注释是用于类,字段还是方法。 让我们说它是方法:所以你在你的注释定义中写这个:

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

接下来你要编写让我们说DirtyChecker类,它将使用reflection来检查方法是否有注释并做一些工作,例如说如果oldValuenewValue相等:

 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; } } 

干杯,米哈尔

要回答第二个问题:您的注释无法返回值。 处理注释的类可以对您的对象执行某些操作。 例如,这通常用于记录。 我不确定是否使用注释来检查对象是否脏是有意义的,除非你想在这种情况下抛出exception或通知某种DirtyHandler

对于你的第一个问题:你真的可以花一些力气自己找到它。 这里有关于stackoverflow和web的足够信息。

CustomAnnotation.java

 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface CustomAnnotation { int studentAge() default 21; String studentName(); String stuAddress(); String stuStream() default "CS"; } 

如何在Java中使用Annotation字段?

TestCustomAnnotation.java

 package annotations; import java.lang.reflect.Method; public class TestCustomAnnotation { public static void main(String[] args) { new TestCustomAnnotation().testAnnotation(); } @CustomAnnotation( studentName="Rajesh", stuAddress="Mathura, India" ) public void testAnnotation() { try { Class cls = this.getClass(); Method method = cls.getMethod("testAnnotation"); CustomAnnotation myAnno = method.getAnnotation(CustomAnnotation.class); System.out.println("Name: "+myAnno.studentName()); System.out.println("Address: "+myAnno.stuAddress()); System.out.println("Age: "+myAnno.studentAge()); System.out.println("Stream: "+myAnno.stuStream()); } catch (NoSuchMethodException e) { } } } Output: Name: Rajesh Address: Mathura, India Age: 21 Stream: CS 

参考