标签:java annotation 注解
package com.annotation.zjc;
import java.lang.annotation.*;
//以下三行是“元注解”,用于指明此注解的生命周期、使用范围和可被文档化
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface Description {
String value();
}
package com.annotation.zjc;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR,ElementType.METHOD})
@Documented
public @interface Resource {
int id();
String name();
String type() default "Object"; //可以给出默认值
}
package com.annotation.zjc;
@Description("Inject use annotation")
//等同于@Description(value="Inject use annotation"),字段名称为value,可以用以上简写模式
public class ApplyAnnotation {
@Resource(id=1,name="zhang",type="person")
public ApplyAnnotation(){
//init...
}
public void execute(Resource r){
System.out.println(r.id()+" "+r.name()+" "+r.type());
}
}
package com.annotation.zjc;
import java.lang.reflect.Constructor;
public class testMain {
public static void main(String[] args){
ApplyAnnotation aa=new ApplyAnnotation();
Class<?> objclass=null;
try{
objclass = Class.forName("com.annotation.zjc.ApplyAnnotation");
}catch(Exception e){}
if(objclass!=null&&objclass.isAnnotationPresent(Description.class)){
Description des=objclass.getAnnotation(Description.class);//获取“注解对象”
System.out.println(des.value());
}
Resource r=null;
if(objclass!=null){
Constructor<?> cons[]=objclass.getConstructors();//反射取得类的构造函数
for(Constructor<?> con:cons){
if(con.isAnnotationPresent(Resource.class)){
r=(Resource)con.getAnnotation(Resource.class);//获取“注解对象”
}
}
}
if(r!=null)
aa.execute(r);
}
}
回顾java Annotation(注解),布布扣,bubuko.com
标签:java annotation 注解
原文地址:http://blog.csdn.net/zjc/article/details/36948641