溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java怎么使用注解和反射簡(jiǎn)化編程

發(fā)布時(shí)間:2021-04-17 12:49:03 來(lái)源:億速云 閱讀:150 作者:小新 欄目:編程語(yǔ)言

這篇文章主要介紹Java怎么使用注解和反射簡(jiǎn)化編程,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

具體如下:

一 點(diǎn)睛

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

二 代碼

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;
  }
}

三 運(yùn)行

Tempreture is 20 AF
Electricity is 100 Ah
SOC is 10 %

以上是“Java怎么使用注解和反射簡(jiǎn)化編程”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI