温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-07-22 16:04:42 来源:亿速云 阅读:105 作者:Leah 栏目:编程语言

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 name() default "methodname";  public String unit() default "unit";}public class ch21_10 {  public static void main( String[] args ) throws Exception {    ch21_10 ch9 = new ch21_10();    Method method[] = ch9.getClass().getMethods();    for (Method method2 : method) {      Annotation annotation = method2.getAnnotation(testAnnoation10.class);      Class<?> ts[] = method2.getParameterTypes();      if (method2.getName().indexOf("getData") == -1) continue;      ArrayList<Object> params = new ArrayList<Object>();      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) annotation;        System.out.println(t9.name() + " is " + method2.invoke(ch9, params.toArray()) + " " + t9.unit());      }    }  }  @testAnnoation10(name = "SOC", unit = "%")  public int getData1( int a ) {    return a;  }  @testAnnoation10(name = "Electricity", unit = "Ah")  public String getData2( String b ) {    return b;  }  @testAnnoation10(name = "Tempreture", unit = "AF")  public int getData3( int a, int b ) {    return a + b;  }}

三 运行

Tempreture is 20 AFElectricity is 100 AhSOC is 10 %

关于Java中怎么利用注解和反射简化编程问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI