java Annotation注解的运用

1、对于其概念和定义就不说了,直接看一下代码。

2、

Description.java

package com.lixx.annotation;

import java.lang.annotation.Documented;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface Description {

String value();

}

Name.java

package com.lixx.annotation;

import java.lang.annotation.Documented;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface Name {

String originate();

String community();

}

JavaEyer.java

package com.lixx.annotation;

@Description(value="javaeye,做最棒的软件开发交流社区")

public class JavaEyer {

private String name;

@Name(originate="创始人:robbin",community="javaEye")

public String getName() {

return name;

}

@Name(originate="创始人:江南白衣",community="springside")

public void setName(String name) {

this.name = name;

}

}

TestAnnotation.java

package com.lixx.annotation;

import java.lang.reflect.Method;

import java.util.HashSet;

import java.util.Set;

public class TestAnnotation {

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

ClassNotFoundException ex ;

String CLASS_NAME = "com.lixx.annotation.JavaEyer";

try {

Class test = Class.forName(CLASS_NAME);

Method[] method = test.getMethods();

boolean flag = test.isAnnotationPresent(Description.class);

if(flag){

Description des = (Description)test.getAnnotation(Description.class);

System.out.println("描述为:"+des.value());

}

/**

* 将javaeyer类中所有用到@Name的全部方法保存到set集合中去

*/

Set<Method> set = new HashSet<Method>();

for(Method methd : method){

boolean otherFlag = methd.isAnnotationPresent(Name.class);

if(otherFlag){

set.add(methd);

}

}

for(Method m : set){

Name name = m.getAnnotation(Name.class);

System.out.println(name.originate()+"  "+"创建的社区:"+name.community());

}

return ;

} catch (ClassNotFoundException e) {

ex = e;

}

if(null != ex){

throw ex;

}

}

}

可以试着运行下....

原文地址:https://www.cnblogs.com/xinzhuangzi/p/4100467.html