java自定义annotation_Java自定义annotation | 学步园

1、 Annotation需要声明为@interface

2、@Target:  表示该注解可以用于什么地方。可用ElementType枚举类型主要有:

TYPE : 类、接口或enum声明

FIELD: 域(属性)声明

METHOD: 方法声明

PARAMETER: 参数声明

CONSTRUCTOR: 构造方法声明

LOCAL_VARIABLE:局部变量声明

ANNOTATION_TYPE:注释类型声明

PACKAGE: 包声明

3、@Retention: 表示需要在什么级别保存该注解信息。

可用RetentionPolicy枚举类型主要有:

SOURCE: 注解将被编译器丢弃。

CLASS  :  注解在class文件中可能。但会被VM丢弃。

RUNTIME: VM将在运行时也保存注解(如果需要通过反射读取注解,则使用该值)。

4、定义一个@ValueBoind的annotation,里面有两个值,一个是enum类型,一个是String类型

@Target(ElementType.METHOD)

@Retention(value=RetentionPolicy.RUNTIME)

@Documented

public @interface ValueBind {

enum fieldType {

STRING, INT

};

fieldType type();

String value();

}

5、定义一个类,给方法加上注解:

public class Student {

private String studentId;

private String name;

private int age;

public String getStudentId() {

return studentId;

}

@ValueBind(type = fieldType.STRING, value = "1001")

public void setStudentId(String studentId) {

this.studentId = studentId;

}

public String getName() {

return name;

}

@ValueBind(type = fieldType.STRING, value = "mary kim")

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

@ValueBind(type = fieldType.INT, value = "25")

public void setAge(int age) {

this.age = age;

}

}

6、利用java反射实现annotation

public class PersistStudent {

public static void main(String[] args) {

try {

Object c = Class.forName("com.test.annotation.Student").newInstance();

Method []methods = c.getClass().getDeclaredMethods();

for (Method method : methods) {

if (method.isAnnotationPresent(ValueBind.class)) {

ValueBind annotation = method.getAnnotation(ValueBind.class);

String type = String.valueOf(annotation.type());

String value = annotation.value();

if ("STRING".equals(type)) {

method.invoke(c, value);

} else {

method.invoke(c, Integer.valueOf(value));

}

}

}

Student student = (Student)c;

System.out.println("studentId = " + student.getStudentId()

+ ", name= " + student.getName() + ", age= " + student.getAge());

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (NumberFormatException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值