自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

在Java的反射中,Class.forName和ClassLoader的區(qū)別

開發(fā) 后端
最近在面試過程中有被問到,在Java反射中Class.forName()加載類和使用ClassLoader加載類的區(qū)別。當時沒有想出來后來自己研究了一下就寫下來記錄一下。

[[379810]]

 最近在面試過程中有被問到,在Java反射中Class.forName()加載類和使用ClassLoader加載類的區(qū)別。當時沒有想出來后來自己研究了一下就寫下來記錄一下。

解釋

在java中Class.forName()和ClassLoader都可以對類進行加載。ClassLoader就是遵循雙親委派模型最終調(diào)用啟動類加載器的類加載器,實現(xiàn)的功能是“通過一個類的全限定名來獲取描述此類的二進制字節(jié)流”,獲取到二進制流后放到JVM中。Class.forName()方法實際上也是調(diào)用的CLassLoader來實現(xiàn)的。

Class.forName(String className);這個方法的源碼是 

  1. @CallerSensitive  
  2.   public static Class<?> forName(String className)  
  3.               throws ClassNotFoundException {  
  4.       Class<?> caller = Reflection.getCallerClass();  
  5.       return forName0(className, true, ClassLoader.getClassLoader(caller), caller);  
  6.   } 

最后調(diào)用的方法是forName0這個方法,在這個forName0方法中的第二個參數(shù)被默認設置為了true,這個參數(shù)代表是否對加載的類進行初始化,設置為true時會類進行初始化,代表會執(zhí)行類中的靜態(tài)代碼塊,以及對靜態(tài)變量的賦值等操作。

也可以調(diào)用Class.forName(String name, boolean initialize,ClassLoader loader)方法來手動選擇在加載類的時候是否要對類進行初始化。Class.forName(String name, boolean initialize,ClassLoader loader)的源碼如下: 

  1. /* @param name       fully qualified name of the desired class  
  2.   * @param initialize if {@code true} the class will be initialized.  
  3.   *                   See Section 12.4 of <em>The Java Language Specification</em> 
  4.   * @param loader     class loader from which the class must be loaded  
  5.   * @return           class object representing the desired class 
  6.   *  
  7.   * @exception LinkageError if the linkage fails  
  8.   * @exception ExceptionInInitializerError if the initialization provoked  
  9.   *            by this method fails  
  10.   * @exception ClassNotFoundException if the class cannot be located by  
  11.   *            the specified class loader  
  12.   *  
  13.   * @see       java.lang.Class#forName(String)  
  14.   * @see       java.lang.ClassLoader 
  15.   * @since     1.2  
  16.   */  
  17.  @CallerSensitive  
  18.  public static Class<?> forName(String name, boolean initialize,  
  19.                                 ClassLoader loader)  
  20.      throws ClassNotFoundException  
  21.  {  
  22.      Class<?> caller = null 
  23.      SecurityManager sm = System.getSecurityManager();  
  24.      if (sm != null) { 
  25.          // Reflective call to get caller class is only needed if a security manager  
  26.          // is present.  Avoid the overhead of making this call otherwise.  
  27.          caller = Reflection.getCallerClass();  
  28.          if (sun.misc.VM.isSystemDomainLoader(loader)) {  
  29.              ClassLoader ccl = ClassLoader.getClassLoader(caller);  
  30.              if (!sun.misc.VM.isSystemDomainLoader(ccl)) {  
  31.                  sm.checkPermission(  
  32.                      SecurityConstants.GET_CLASSLOADER_PERMISSION);  
  33.              }  
  34.          }  
  35.      }  
  36.      return forName0(name, initialize, loader, caller);  
  37.  } 

源碼中的注釋只摘取了一部分,其中對參數(shù)initialize的描述是:*if {@code true} the class will be initialized.*意思就是說:如果參數(shù)為true,則加載的類將會被初始化。

舉例

下面還是舉例來說明結(jié)果吧:

一個含有靜態(tài)代碼塊、靜態(tài)變量、賦值給靜態(tài)變量的靜態(tài)方法的類 

  1. public class ClassForName {  
  2.     //靜態(tài)代碼塊  
  3.     static {  
  4.         System.out.println("執(zhí)行了靜態(tài)代碼塊");  
  5.     }  
  6.     //靜態(tài)變量  
  7.     private static String staticFiled = staticMethod();  
  8.     //賦值靜態(tài)變量的靜態(tài)方法  
  9.     public static String staticMethod(){  
  10.         System.out.println("執(zhí)行了靜態(tài)方法");  
  11.         return "給靜態(tài)字段賦值了"; 
  12.     }} 

使用Class.forName()的測試方法: 

  1. @Testpublic void test44(){  
  2.         try {  
  3.             Class.forName("com.eurekaclient2.client2.ClassForName");  
  4.             System.out.println("#########-------------結(jié)束符------------##########");  
  5.         } catch (ClassNotFoundException e) {  
  6.             e.printStackTrace();  
  7.         }} 

運行結(jié)果: 

  1. #########-------------結(jié)束符------------########## 

根據(jù)運行結(jié)果得出Class.forName加載類是將類進了初始化,而ClassLoader的loadClass并沒有對類進行初始化,只是把類加載到了虛擬機中。

應用場景

在我們熟悉的Spring框架中的IOC的實現(xiàn)就是使用的ClassLoader。

而在我們使用JDBC時通常是使用Class.forName()方法來加載數(shù)據(jù)庫連接驅(qū)動。這是因為在JDBC規(guī)范中明確要求Driver(數(shù)據(jù)庫驅(qū)動)類必須向DriverManager注冊自己。

以MySQL的驅(qū)動為例解釋: 

  1. public class Driver extends NonRegisteringDriver implements java.sql.Driver {    
  2.     // ~ Static fields/initializers    
  3.     // ---------------------------------------------    
  4.     //    
  5.     // Register ourselves with the DriverManager    
  6.     //    
  7.     static {    
  8.         try {    
  9.             java.sql.DriverManager.registerDriver(new Driver());   
  10.         } catch (SQLException E) {    
  11.             throw new RuntimeException("Can't register driver!");    
  12.         }  
  13.     }    
  14.     // ~ Constructors   
  15.     // -----------------------------------------------------------   
  16.      /**   
  17.      * Construct a new driver and register it with DriverManager   
  18.      *    
  19.      * @throws SQLException   
  20.      *             if a database error occurs.  
  21.      */    
  22.     public Driver() throws SQLException {    
  23.         // Required for Class.forName().newInstance()      }   

我們看到Driver注冊到DriverManager中的操作寫在了靜態(tài)代碼塊中,這就是為什么在寫JDBC時使用Class.forName()的原因了。

好了,今天就寫到這了,最近在面試,遇到了很多問題,也學習了不少,雖然很累,但是也讓人成長了不少,畢竟面試就是一個脫皮的過程,會遇到各種企業(yè)各種面試官各種問題,各種場景。給自己加油吧,找一個最少能讓自己干個幾年的公司,別總是讓我遇到工作了沒多久公司就垮掉的這種就行了。要不我也很無奈啊。 

 

責任編輯:龐桂玉 來源: 互聯(lián)網(wǎng)程序員
相關推薦

2009-05-19 14:13:46

.NET反射Assembly

2021-08-24 10:25:19

thisclassJava

2021-08-02 07:57:03

SynchronizeJava語言

2011-11-23 09:39:33

JavaClassLOader機制

2021-06-30 10:32:33

反射多態(tài)Java

2021-11-10 15:18:16

JavaGo命令

2011-12-06 10:48:32

Java

2021-08-31 06:37:35

Java 語言 Java 基礎

2023-03-15 16:00:14

JavaJava new開發(fā)

2009-06-17 09:40:01

JBoss的class

2021-08-17 11:14:49

VoidJSTS

2023-10-12 08:25:18

Javaequals內(nèi)存

2011-05-20 13:45:30

Java

2009-07-08 14:06:22

ClassLoaderJDK源碼

2020-09-23 09:08:05

typescript

2010-08-30 10:52:39

CSSclassid

2010-08-23 14:16:17

DIVclassid

2011-04-06 08:57:07

C++java多態(tài)

2010-10-08 15:17:47

JavaScriptJava

2012-03-01 14:04:03

Java
點贊
收藏

51CTO技術棧公眾號