网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

Java中怎么通过反射访问注解信息

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

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:申请域名、网页空间、营销软件、网站建设、洱源网站维护、网站推广。

一 点睛

利用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中怎么通过反射访问注解信息
URL标题:http://bjjierui.cn/article/ijeice.html

其他资讯