Java中怎么利用注解和反射簡(jiǎn)化編程,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
創(chuàng)新互聯(lián)公司是工信部頒發(fā)資質(zhì)IDC服務(wù)器商,為用戶(hù)提供優(yōu)質(zhì)的成都移動(dòng)服務(wù)器托管服務(wù)一 點(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 AFElectricity is 100 AhSOC is 10 %
關(guān)于Java中怎么利用注解和反射簡(jiǎn)化編程問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
本文題目:Java中怎么利用注解和反射簡(jiǎn)化編程-創(chuàng)新互聯(lián)
URL標(biāo)題:http://www.rwnh.cn/article46/gepeg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航、網(wǎng)站營(yíng)銷(xiāo)、ChatGPT、定制網(wǎng)站、網(wǎng)站策劃、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容