资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

怎么在Java中利用反射访问注解信息例

本篇文章为大家展示了怎么在Java中利用反射访问注解信息例,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

创新互联主要从事成都网站建设、成都做网站、网页设计、企业做网站、公司建网站等业务。立足成都服务望谟,十多年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792

利用Java的反射机制,可以访问注解信息。比如在调用某个方法时,需要知道该方法的一些基本信息,而这些信息又需要动态获取时,利用发射获取注解信息是一个比较理想的处理方式。

二 实战——访问类的某个成员方法的注解信息

1 代码

import java.lang.annotation.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;
import java.lang.reflect.Method;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface testAnnoation8 {
  public String name() default "methodname";
  public String unit() default "unit";
}
public class ch21_8 {
  public String aString;
  public static void main( String[] args ) {
    try {
      ch21_8 ch8 = new ch21_8();
      Method method = ch8.getClass().getMethod("getData1");
      Annotation ans[] = method.getAnnotations();
      for (Annotation annotation : ans) {
        System.out.println(annotation);
      }
      Annotation annotation = method.getAnnotation(testAnnoation8.class);
      System.out.println(annotation);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Deprecated
  @testAnnoation8(name = "SOC", unit = "%")
  public void getData1() {
  }
}

2 运行

@java.lang.Deprecated()
@testAnnoation8(name=SOC, unit=%)
@testAnnoation8(name=SOC, unit=%)

三 实战——访问类的某个成员方法的注解信息

1 代码

import java.lang.annotation.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;
import java.lang.reflect.Method;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface testAnnoation9{
   public String name() default "methodname";
   public String unit() default "unit";
}
public class ch21_9 {
  public String aString;
  public static void main(String[] args) {
   try {
     ch21_9 ch9=new ch21_9();
     Method method=ch9.getClass().getMethod("getData1");
     Annotation annotation=method.getAnnotation(testAnnoation9.class);
     testAnnoation9 t9=(testAnnoation9)annotation;
     System.out.println("name value is "+t9.name()+"; unit is "+t9.unit());
   } catch (Exception e) {
     e.printStackTrace();
   }
  }
  @Deprecated
  @testAnnoation9(name = "SOC", unit = "%")
  public void getData1(){
  }
}

2 运行

name value is SOC; unit is %

上述内容就是怎么在Java中利用反射访问注解信息例,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。


本文标题:怎么在Java中利用反射访问注解信息例
网页路径:http://cdkjz.cn/article/ipgdio.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220