简单实践
定义注解
import java.lang.annotation.*;
@Documented
@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface UserAnnotation {
String name() default "test";
enum Addrass{Beijing,Shanghang,shanxi};
Class runtime() default Object.class;
}
注解使用
import annotation.an.UserAnnotation;
public class Entity {
@UserAnnotation(name = "lalallala")
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
注解行为添加
import annotation.an.UserAnnotation;
import java.lang.reflect.Field;
public class Utils {
public static void getEntityInfo(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
for (Field field: fields) {
if(field.isAnnotationPresent(UserAnnotation.class)){
UserAnnotation d = (UserAnnotation) field.getAnnotation(UserAnnotation.class);
System.out.println(d.name());
}
}
}
}
测试
import annotation.Entity.Entity;
import annotation.Entity.Utils;
public class Test{
public static void main(String []args){
Utils.getEntityInfo(Entity.class);
}
}