读书人

java引文定义

发布时间: 2012-10-07 17:28:51 作者: rapoo

java注解定义
//三个参数 :Target表示这个注解能应用在类型上
//Retention 表示保持策略为运行时,就算加载类,这个注解能要加载。
//Documented 表示这个注解能体现在javadoc中
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Description
{
String value();
}

// 注意这里的@Target与@Description里的不同,参数成员也不同
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Name
{
String originate();

String community();
}

使用注解:
@Description("2121212121212")
public class JavaEyer
{
@Name(originate = "创始人:robbin", community = "javaEye")
public String getName()
{
return null;
}

@Name(originate = "创始人:江南白衣", community = "springside")
public String getName2()
{
return "666666666666666666666";
}
}

注解使用
public class TestAnnotation
{
/**
* author lighter 说明:具体关天Annotation的API的用法请参见javaDoc文档
*/
public static void main(String[] args)
throws Exception
{
String CLASS_NAME = "com.JavaEyer";
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());
System.out.println("-----------------");
}

// 把JavaEyer这一类有利用到@Name的全部方法保存到Set中去
Set<Method> set = new HashSet<Method>();
for (int i = 0; i < method.length; i++)
{
boolean otherFlag = method[i].isAnnotationPresent(Name.class);
if (otherFlag)
set.add(method[i]);
}
for (Method m : set)
{
Name name = m.getAnnotation(Name.class);
System.out.println(name.originate());
System.out.println("创建的社区:" + name.community());
}
}
}

读书人网 >编程

热点推荐