栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java使用注解和反射简化编程的方法示例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java使用注解和反射简化编程的方法示例

本文实例讲述了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 params = new ArrayList();
      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数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号