您的位置:首页 > 编程语言 > Java开发

Java自定义annotation

2012-12-12 19:44 330 查看
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();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: