之前代碼有一個邏輯,是在初始化時讀取某個包下的所有class文件,放入到一個HashMap里。代碼運行過程中,通過Key獲取到對應class的全路徑名,最后通過Class.forName(className).getDeclaredConstructor().newInstance()獲取實例對象。
后來同事看到了代碼,對這個HashMap里存儲方式提出了建議,之前的Map是<String,String>完全可以改成<String,Class>
后來我測試了一下兩者實例化一個對象的速度:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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反射獲取類實例并調用私有方法
我就廢話不多說了,大家還是直接看代碼吧~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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" ); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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://blog.csdn.net/qq_39622065/article/details/108770699