不多說,先看例子,通過例子來說這個自定義註解。
自己定義了一個註解類testType:
package com.zhudan.test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD })
public @interface testType {
int length() default 255;
String description() default "";
}
自己建立一個user類:
package com.zhudan.test;
/*
*
*/
public class testUser {
@testType(length=50,description="名字")
private String name;
@testType(length=50,description="年齡")
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
test類測試:
package com.zhudan.test;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class test {
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Field[] fields = testUser.class.getDeclaredFields();
for(Field field : fields){
System.out.println(field);
//獲取自定義註解類
testType type = field.getAnnotation(testType.class);
int s=type.length();
String ss=type.description();
System.out.println(ss);
int lengString=type.length();
System.out.println(lengString);
}
}
}
效果如下:
自定義註解,當然這只是一個小小的demo,我只是想通過這個小小的demo告訴自己自定義註解的好處,該怎麼用,最基本的方法是什麼,淺嘗輒止,爲以後的進一步理解做好準備。