標籤:string 表示 value equal retention type document src round
一、自訂註解1. 使用關鍵字 @interface2. 預設情況下,註解可以修飾 類、方法、介面等。3. 如下為一個基本的註解例子:
//註解中的成員變數非常像定義介面public @interface MyAnnotation { //不帶有預設值 String name(); //帶有預設值 int age() default 20;}
4. Reflect中3個常見方法解讀
- getAnnotion(Class<T> annotationClass) 返回該元素上存在的,指定類型的註解,如果沒有返回null
- Annotation[] getAnnotations() 返回該元素上所有的註解。
- boolean isAnnotationPersent(Class<? extends Annotation> annotationClass) 判斷該院上上是否含有制定類型的注釋。
二、元註解
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface ValueBind { filedType type(); String value() default "SUSU"; enum filedType { STRING, INT }}
其中@Target 和 @Retention為元註解。
- @Retention有如下幾種取值:
- 其中通常都是RetentionPolicy.RUNTIME
@Target有如下幾個取值:
@Inherited 表示該註解具有繼承性。三、Demo
1. ValueBind註解
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface ValueBind { filedType type(); String value() default "SUSU"; enum filedType { STRING, INT }}
2. Person類
public class Person implements Serializable { private String name; private int age; public String getName() { return name; } @ValueBind(type = ValueBind.filedType.STRING, value = "LCF") public void setName(String name) { this.name = name; } public int getAge() { return age; } @ValueBind(type = ValueBind.filedType.INT, value = "21") public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; }}
3. Main方法
import java.lang.reflect.Method;public class Main { public static void main(String[] args) throws Exception { Object person = Class.forName("Person").newInstance(); //以下擷取的是:類的註解 // Annotation[] annotations = person.getClass().getAnnotations(); Method[] methods = person.getClass().getMethods(); for (Method method : methods) { //如果該方法上面具有ValueBind這個註解 if (method.isAnnotationPresent(ValueBind.class)) { //通過這個註解可以擷取到註解中定義的 ValueBind annotation = method.getAnnotation(ValueBind.class); if (annotation.type().equals(ValueBind.filedType.STRING)) { method.invoke(person, annotation.value()); } else { method.invoke(person, Integer.parseInt(annotation.value())); } } } System.out.println(person); }}
輸出結果:Person{name=‘LCF‘, age=21}
Java註解Annotation學習筆記