温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-10-30 17:24:38 来源:亿速云 阅读:187 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关Java反射获取实例的速度对比,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

  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<&#63;> 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反射获取实例的速度对比,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI