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

时间:2012-09-04 09:00:10

标签: java annotations

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

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

假设我创建了一个界面:

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

我的问题是

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

3 个答案:

答案 0 :(得分:20)

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

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

接下来,你必须写一下让我们说DirtyChecker类,它将使用反射来检查方法是否有注释并做一些工作,比如说如果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;
    }
}

干杯, 米甲

答案 1 :(得分:2)

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

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

答案 2 :(得分:2)

<强> 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<? extends TestCustomAnnotation> 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

Reference

相关问题