Java使用注解和反射簡化編程的方法示例
更新時間:2019年10月29日 08:38:02 作者:cakincqm
這篇文章主要介紹了Java使用注解和反射簡化編程的方法,結合實例形式分析了java使用注解和反射調用大量函數(shù)簡化編程的相關操作技巧,需要的朋友可以參考下
本文實例講述了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 ch11_10 { public static void main( String[] args ) throws Exception { ch11_10 ch9 = new ch11_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相關內容感興趣的讀者可查看本站專題:《Java面向對象程序設計入門與進階教程》、《Java數(shù)據(jù)結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
Java 單向隊列及環(huán)形隊列的實現(xiàn)原理
本文主要介紹了Java 單向隊列及環(huán)形隊列的實現(xiàn)原理,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10SpringBoot指標監(jiān)控功能實現(xiàn)
這篇文章主要介紹了SpringBoot指標監(jiān)控功能實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06SpringBoot+MyBatis-Plus實現(xiàn)分頁功能
在SpringBoot項目中,結合MyBatis-Plus(簡稱MP)可以非常方便地實現(xiàn)分頁功能,MP為開發(fā)者提供了分頁插件PaginationInterceptor,只需簡單配置即可使用,本文給大家介紹了SpringBoot+MyBatis-Plus實現(xiàn)分頁功能,文中通過代碼示例給大家介紹的非常詳細,需要的朋友可以參考下2024-01-01