Java反射获取实例速度 Java反射获取实例的速度对比分析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java反射获取实例速度 Java反射获取实例的速度对比分析

天上飞下一毛雪   2021-03-16 我要评论
想了解Java反射获取实例的速度对比分析的相关内容吗,天上飞下一毛雪在本文为您仔细讲解Java反射获取实例速度的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,反射获取实例,速度,下面大家一起来学习吧。

之前代码有一个逻辑,是在初始化时读取某个包下的所有class文件,放入到一个HashMap里。代码运行过程中,通过Key获取到对应class的全路径名,最后通过Class.forName(className).getDeclaredConstructor().newInstance()获取实例对象。

后来同事看到了代码,对这个HashMap里存储方式提出了建议,之前的Map是<String,String>完全可以改成<String,Class>

后来我测试了一下两者实例化一个对象的速度:

  public static void main(String[] args) {
    try {
      int MAX = 100000;
      for (int count = 0; count < 50; count++) {
        System.out.println("====第" + count+"次");
 
        long s1 = System.currentTimeMillis();
        for (int i = 0; i < MAX; i++) {
          Person o = (Person)Class.forName("com.qingtai.domin.Person").newInstance();
        }
        long e1 = System.currentTimeMillis();
        System.out.println("1_duration:" + (e1 - s1));
 
        long s2 = System.currentTimeMillis();
        Class clazz = Class.forName("com.qingtai.domin.Person");
        for (int i = 0; i < MAX; i++) {
          Person person = (Person) clazz.newInstance();
        }
        long e2 = System.currentTimeMillis();
        System.out.println("2_duration:" + (e2 - s2));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

输出:

====第39次 1_duration:72 2_duration:3 ====第40次 1_duration:79 2_duration:12 ====第41次 1_duration:92 2_duration:8 ====第42次 1_duration:80 2_duration:5

结论:

Map的value不存储全路径名,在初始化的时候Map的value直接存储Class对象,在反射过程中速度提升很大。

补充知识:java反射获取类实例并调用私有方法

我就废话不多说了,大家还是直接看代码吧~

public class TestReflect {//测试类
 
 public void mPublic() {//访问权限最大
 System.out.println("public run");
 }
 
 protected void mProtected() {//同包下才能访问(实验对象)
 System.out.println("protected run");
 }
 
 private void mPrivate() {//只有本类中才能访问(实验对象)
 System.out.println("private run");
 } 
}
 public static void main(String[] args) throws Exception {
 Class<?> class1 = null;
 // 反射获取类实例,用的最多的就是jdbc获取驱动的时候就是用Class.forName("xxx");
 // 一般采用这种形式
 class1 = Class.forName("com.xxx.TestReflect");
 // class1 = new TestReflect().getClass();
 // class1 = TestReflect.class;
 
 // 类实例化,到这里就可以访问TestReflect类的public属性的成员方法和成员变量了
 TestReflect tr = (TestReflect) class1.newInstance();
 
 // 通过java.lang.Class类得到一个Method对象
 // api中java.lang.Class.getDeclaredMethod方法介绍
 // 返回一个 Method 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明方法。
   Method method = class1.getDeclaredMethod("mPrivate");
   Method method1 = class1.getDeclaredMethod("mProtected");
   
   //将此对象的 accessible 标志设置为指示的布尔值。
 //值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。
 //值为 false 则指示反射的对象应该实施 Java 语言访问检查。
   method.setAccessible(true); 
   method1.setAccessible(true);
   
   // 调用该方法
   method.invoke(tr);
   method1.invoke(tr);
 }

以上这篇Java反射获取实例的速度对比分析就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们