2012-06-22 2 views
1

나는 Class.forName(String className)이 클래스를로드하는 데 Thread.currentThread().getContextClassLoader()을 사용했지만 외관상 그렇지 않다는 인상을 받았다.Class.forName은 기본적으로 어떤 ClassLoader를 사용합니까?

제 질문은 입니다. 어떤 ClassLoader가 기본적으로 Class.forName을 사용합니까? 그게 ClassLoader.getSystemClassLoader()입니까?

Thread.currentThread().getContextClassLoader()ClassLoader.getSystemClassLoader()의 차이점은 무엇입니까?

답변

7

호출자의 클래스 로더를 사용합니다. the documentation :

주어진 문자열 이름을 사용하여 클래스 또는 인터페이스와 연결된 Class 객체를 반환합니다. 이 메소드의 호출은 다음과 같습니다.

Class.forName(className, true, currentLoader) 

여기서 currentLoader는 현재 클래스의 정의 클래스 로더를 나타냅니다.

+0

그래서 당신은 의미 그들 중 누구도? 수업이 그들 중 하나에서로드되지 않았다면? –

+3

@ AdelBoutros : 정확합니다. 그것은 호출 클래스를로드 한 것입니다. –

1

invoker 클래스 로더를 사용합니다. 의 forName()의 소스 코드 :

public static Class<?> forName(String className) 
       throws ClassNotFoundException { 
     return forName0(className, true, ClassLoader.getCallerClassLoader()); 
    } 

그리고 getCallerClassLoader는()입니다 :

static ClassLoader getCallerClassLoader() { 
     // NOTE use of more generic Reflection.getCallerClass() 
     Class caller = Reflection.getCallerClass(3); 
     // This can be null if the VM is requesting it 
     if (caller == null) { 
      return null; 
     } 
     // Circumvent security check since this is package-private 
     return caller.getClassLoader0(); 
    } 

그리고이 방법에 대한 설명은 다음과 같습니다

// Returns the invoker's class loader, or null if none. 
관련 문제