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

Java自定义Annotation学习

2012-02-03 00:08 260 查看
本次学习的目标是为了获取如下Java类成员中ID的值: Java代码 package com.perficient.annotation;

public class WebPage
{

@Identifier(id= "A")

public String
buttonA;

@Identifier(id= "B")

public String
buttonB;

}

package com.perficient.annotation;public class WebPage { @Identifier(id= "A") public String buttonA; @Identifier(id= "B") public String buttonB;}[/pre]

创建自定义的Annotation: Java代码 package com.perficient.annotation;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

public @interface Identifier
{

public String
id();

}

package com.perficient.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME)
public @interface Identifier { public String id(); }[/pre]

注意:Target一定要给予正确的值,如果是类成员的话用Field,是方法要用Method

编写测试类 Java代码 package com.perficient.annotation;

import java.lang.reflect.Field;

public class AnnotationTest
{

public static void main(String[]
args) throws ClassNotFoundException
{

String className = "com.perficient.annotation.WebPage";

Class<?> test = Class.forName(className);

Field[] fields = test.getFields();

for (Field
field : fields){

System.out.println("The
field Name is:" + field);

boolean flag
= field.isAnnotationPresent(Identifier.class);

if (flag)
{

Identifier idt = (Identifier) field

.getAnnotation(Identifier.class);

System.out.println("Id
is:" + idt.id());

} else {

System.out.println("The
annotation can't be found");

}

}

}

}

package com.perficient.annotation;import java.lang.reflect.Field;public class AnnotationTest { public static void main(String[] args) throws ClassNotFoundException { String className = "com.perficient.annotation.WebPage"; Class<?> test = Class.forName(className);
Field[] fields = test.getFields(); for (Field field : fields){ System.out.println("The field Name is:" + field); boolean flag = field.isAnnotationPresent(Identifier.class); if (flag) { Identifier
idt = (Identifier) field .getAnnotation(Identifier.class); System.out.println("Id is:" + idt.id()); } else { System.out.println("The annotation can't be found"); }
} }}[/pre]

注意:如果是Method,需要使用getDeclaredMethods(),如果用getMethods()不会返回我们所需要的结果

输出结果: Java代码The field Name is:public java.lang.String
com.perficient.annotation.WebPage.buttonA

Id is:A

The field Name is:public java.lang.String
com.perficient.annotation.WebPage.buttonB

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