java自定义注解教程
1、定义注解类
@Documented
@Inherited
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface IniterValue {
public String value() default "";
}
2、定义使用注解的类
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。@Data
public class User {
@IniterValue(value = "2")
private Integer age;
@IniterValue(value = "小明")
private String name;
}
3、定义注解解析器
public class UserFactory {
public static <T> T create(Class<T> t) throws IllegalAccessException, InstantiationException {
T t1 = t.newInstance();
Field[] fields = t1.getClass().getDeclaredFields();
for (Field field:fields) {
if(field.isAnnotationPresent(IniterValue.class)){
IniterValue annotation = field.getAnnotation(IniterValue.class);
try {
field.setAccessible(true);
Class<?> type = field.getType();
Object obj=null;
if(type == Integer.class){
obj = Integer.valueOf(annotation.value());
}
if(type==String.class){
obj=annotation.value();
}
field.set(t1,obj);
// method.invoke(t1,annotation.value(),annotation.intValue());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return t1;
}
}
4、测试
public class Test {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
User user = UserFactory.create(User.class);
System.out.println(user.getAge());
}
}
更多精彩

