Java反射获取实例的速度对比分析
#代码知识 发布时间: 2026-01-12
之前代码有一个逻辑,是在初始化时读取某个包下的所有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反射获取实例的速度对比分析就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
代码知识SEO上一篇 : python调用摄像头的示例代码
下一篇 : IDEA报错:Unable to save settings Failed to save settings
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!