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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12260037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:12:59  来源:igfitidea点击:

How to create custom annotation in java?

javaannotations

提问by psisodia

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 booleanvalue.

我想在 java 中为DirtyChecking. 就像我想使用此注释比较两个字符串值,比较后它将返回一个boolean值。

For instance: I will put @DirtyCheck("newValue","oldValue")over properties.

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

Suppose I made an interface:

假设我做了一个接口:

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

My Questions are:

我的问题是

  1. Where I make a class to create a method for comparison for two string values? I mean, how this annotation notifies that this method I have to call?
  2. How to retreive returning values of this method ?
  1. 我在哪里创建一个类来创建一个比较两个字符串值的方法?我的意思是,这个注释如何通知我必须调用这个方法?
  2. 如何检索此方法的返回值?

回答by Michal

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 DirtyCheckerclass which will use reflection to check if method has annotation and do some job for example say if oldValueand newValueare equal:

接下来你必须编写让我们说的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;
    }
}

Cheers, Michal

干杯,迈克尔

回答by Kai

To answer your second question: your annotation can't return a value. The class which processes your annotation can do something with your object. This is commonly used for logging for example. I'm not sure if using an annotation for checking if an object is dirty makes sense except you want to throw an exception in this case or inform some kind of DirtyHandler.

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

For your first question: you could really spent some effort in finding this yourself. There are enough information here on stackoverflow and the web.

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

回答by Rajesh Dixit

CustomAnnotation.java

自定义注解.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";
}

How to use the field of Annotation in Java?

Java中如何使用Annotation的字段?

TestCustomAnnotation.java

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

参考