Java中怎么利用注解和反射簡化編程-創(chuàng)新互聯(lián)

Java中怎么利用注解和反射簡化編程,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

創(chuàng)新互聯(lián)公司是工信部頒發(fā)資質(zhì)IDC服務器商,為用戶提供優(yōu)質(zhì)的成都移動服務器托管服務

一 點睛

當調(diào)用大量方法,可以使用反射和注解簡化編程。

二 代碼

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中怎么利用注解和反射簡化編程問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關知識。

本文題目:Java中怎么利用注解和反射簡化編程-創(chuàng)新互聯(lián)
URL標題:http://bm7419.com/article46/gepeg.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導航、網(wǎng)站營銷、ChatGPT、定制網(wǎng)站、網(wǎng)站策劃、網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)