Java怎么使用注解和反射简化编程

  介绍

这篇文章主要介绍Java怎么使用注解和反射简化编程,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

具体如下:

<强>一点睛

当调用大量方法,可以使用反射和注解简化编程。

<强>二代码

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;   import  java.util.ArrayList;   @Documented   @Retention (RetentionPolicy.RUNTIME)   @Target (ElementType.METHOD)   @interface  testAnnoation10  {   public 才能;String 名称(),default “methodname";   public 才能;String 单位(),default “unit";   }   public  class  ch21_10  {   public 才能;static  void 主要(String[]大敌;args ), throws  Exception  {   ,,,ch21_10  ch9 =, new  ch21_10 ();   ,,,Method 方法[],=,ch9.getClass () .getMethods ();   ,,,for  (Method  method2 :方法),{   ,,,,,Annotation  Annotation =, method2.getAnnotation (testAnnoation10.class);   ,,,,,Class<?祝辞,ts [],=, method2.getParameterTypes ();   ,,,,,if  (method2.getName () .indexOf (“getData"),==, 1),继续;   ,,,,,ArrayList, params =, new  ArrayList ();   ,,,,,for  (Class<?祝辞,class1 :, ts), {   ,,,,,,,if  (class1.getSimpleName () .equals (“int")), {   ,,,,,,,,,params.add (10);   ,,,,,,,}   ,,,,,,,if  (class1.getSimpleName () .equals (“String")), {   ,,,,,,,,,params.add (“100”);   ,,,,,,,}   ,,,,,}   ,,,,,if  (annotation  !=, null), {   ,,,,,,,testAnnoation10  t9 =, (testAnnoation10),注释;   ,,,,,,,System.out.println (t9.name (), +,“, is “, +, method2.invoke (ch9, params.toArray ()), +,,,,, +, t9.unit ());   ,,,,,}   ,,,}   ,,}   @testAnnoation10才能(=name “SOC",, unit =,“%”)   public 才能;int  getData1 (, int  a ), {   ,,,return ;   ,,}   @testAnnoation10才能(=name “Electricity",, unit =,“Ah")   public 才能;String  getData2 (, String  b ), {   ,,,return  b;   ,,}   @testAnnoation10才能(=name “Tempreture",, unit =,“AF")   public 才能;int  getData3 (, int ,, int  b ), {   ,,,return  a  +, b;   ,,}   }

<强>三运行

温度是20 AF
电力是100啊
SOC是10%

以上是“Java怎么使用注解和反射简化编程”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!

Java怎么使用注解和反射简化编程

Copyright © 2020-2023 feiqueyun.cn. All Rights Reserved. 肥雀云_南京肥雀信息技术有限公司版权所有 南京肥雀信息技术有限公司 苏ICP备16063723号-5