成都创新互联网站制作重庆分公司

Java怎么使用注解和反射简化编程

这篇文章主要介绍Java怎么使用注解和反射简化编程,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

成都创新互联公司专注于企业成都全网营销、网站重做改版、水富网站定制设计、自适应品牌网站建设、H5页面制作商城网站建设、集团公司官网建设、成都外贸网站建设公司、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为水富等各大城市提供网站开发制作服务。

具体如下:

一 点睛

当调用大量方法,可以使用反射和注解简化编程。

二 代码

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 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怎么使用注解和反射简化编程
分享链接:http://cxhlcq.com/article/ijdioi.html

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部