导读 这篇文章主要介绍了Java反射获取实例的速度对比分析,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

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

后来我测试了一下两者实例化一个对象的速度:
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反射获取实例的速度对比分析就是小编分享给大家的全部内容了,希望能给大家一个参考。

原文来自:https://www.jb51.net/article/196706.htm

本文地址:https://www.linuxprobe.com/java-six-linux.html编辑:向金平,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/