這篇文章主要介紹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 AF
Electricity is 100 Ah
SOC is 10 %
以上是“Java怎么使用注解和反射簡化編程”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注創新互聯網站建設公司行業資訊頻道!
另外有需要云服務器可以了解下創新互聯建站m.newbst.com,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
當前題目:Java怎么使用注解和反射簡化編程-創新互聯
標題鏈接:http://m.newbst.com/article38/depjpp.html
成都網站建設公司_創新互聯,為您提供商城網站、靜態網站、軟件開發、網頁設計公司、用戶體驗、網站建設
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯