[英]How to create custom annotation in java?
我想在Java中為DirtyChecking
創建自定義注釋。 就像我想使用此注釋比較兩個字符串值,並在比較后將返回一個boolean
值。
例如:我將@DirtyCheck("newValue","oldValue")
放在屬性上。
假設我創建了一個界面:
public @interface DirtyCheck {
String newValue();
String oldValue();
}
我的問題是 :
首先,您需要標記注釋是用於類,字段還是方法。 讓我們說它是方法:所以你在你的注釋定義中寫這個:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DirtyCheck {
String newValue();
String oldValue();
}
接下來你要編寫讓我們說DirtyChecker
類,它將使用反射來檢查方法是否有注釋並做一些工作,比如說如果oldValue
和newValue
相等:
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;
}
}
干杯,米哈爾
要回答第二個問題:您的注釋無法返回值。 處理注釋的類可以對您的對象執行某些操作。 例如,這通常用於記錄。 我不確定是否使用注釋來檢查對象是否臟是有意義的,除非你想在這種情況下拋出異常或通知某種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<? 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.