不多说,先看例子,通过例子来说这个自定义注解。
自己定义了一个注解类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告诉自己自定义注解的好处,该怎么用,最基本的方法是什么,浅尝辄止,为以后的进一步理解做好准备。