码迷,mamicode.com
首页 > 其他好文 > 详细

获取不到方法的注解

时间:2014-11-20 12:01:52      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   java   for   on   

注解是不干扰原来的代码的执行的,起到一种标识作用,让第三方的注解工具来提

取注解,来完成所需的任务。

package two.zj;

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;
@Documented
@Retention<span style="color:#ff0000;">(</span><span style="background-color: rgb(255, 0, 0);">RetentionPolicy.RUNTIME</span><span style="color:#ff0000;">)</span>
@Target(ElementType.METHOD)
public @interface TestZJ {
	public int id() default 1;
	public String name() default "nametest";
	public String value() ;
	public abstract int [] intt();
	public abstract TestEnum[] tenum();
	
	
}
package two;


import two.zj.TestEnum;
import two.zj.TestZJ;
public class UserAnn {
<span style="white-space:pre">	</span>/**
<span style="white-space:pre">	</span> * @param user
<span style="white-space:pre">	</span> * @return user
<span style="white-space:pre">	</span> */
<span style="white-space:pre">	</span>@TestZJ(id=22,name="liyy", intt = { 0,1,2,3 }, value = "", tenum = {TestEnum.TEST1})
<span style="white-space:pre">	</span>public User getUser(User user) {
<span style="white-space:pre">		</span>return user;
<span style="white-space:pre">	</span>}


}
package two;


import java.lang.reflect.Method;


import two.zj.TestZJ;


public class Testmain {


public static void main(String[] args) throws ClassNotFoundException {
// Class class1 = Class.forName("two.UserAnn");
Class class1 = UserAnn.class;
Method [] methods = class1.getDeclaredMethods();
for(Method method:methods){
TestZJ annotations = method.getAnnotation(TestZJ.class);
if(annotations !=null){
System.out.println(annotations.id());
}
}
}
}

当注解类TestZJ中的@Retention(RetentionPolicy.RUNTIME)   为source 或者class 时候 反射是获取不到注解类的,因为jdk用说明

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,


    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,


    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

SOURCE在编译的c字节码中去掉注解,CLASS 字节码中有注解但是不加载到虚拟机,RUNTIME可以通过反射获取到注解信息,而注解框架也是采用的这种原理。



获取不到方法的注解

标签:style   blog   io   ar   color   sp   java   for   on   

原文地址:http://blog.csdn.net/liyunyun6/article/details/41309975

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!