2010-12-03 2 views

답변

12

런타임에로드됩니다.

정적은 변수가 클래스에 속하지 않으며 클래스의 인스턴스가 아니라는 것을 의미합니다. 따라서 각 정적 변수에는 하나의 값만 있고, 클래스의 인스턴스가 n 개있는 경우에는 n 값이 아닙니다.

+0

실행 파일을 시작할 때 여러 클래스가 있으면 모든 정적 변수가 힙에로드됩니까? – committedandroider

+1

@committedandroider : 좀 더 복잡합니다. 정적 변수는 클래스를 사용하기 바로 전에 초기화됩니다. – Ralph

4

클래스가로드되는 런타임입니다. - Have a look at initialization

+2

런타임에 클래스가로드 될 때 또는 해당 필드가 처음 참조 될 때를 의미합니까? – Bhushan

1

컴파일 타임에 변수를로드 하시겠습니까? 변수는 해당 클래스가로드 될 때 이 초기화 된입니다. JVMS을 참조하십시오.

74

컴파일러는 런타임시 값을 계산하는 대신 값을 바이트 코드에 포함하여 인라인 가능 정적 최종 필드를 최적화합니다. 필드를 최적화합니다.

처음으로 클래스를로드 할 때 클래스 로더가 JVM을 실행하고 클래스를로드하면 정적 블록이나 필드가 JVM에 '로드'되어 액세스 할 수있게됩니다. .

데모 :

public class StaticDemo { 

// a static initialization block, executed once when the class is loaded 
static { 
    System.out.println("Class StaticDemo loading..."); 
} 

// a constant 
static final long ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000; 

// a static field 
static int instanceCounter; 

// a second static initialization block 
// static members are processed in the order they appear in the class 
static { 
    // we can now acces the static fields initialized above 
    System.out.println("ONE_DAY_IN_MILLIS=" + ONE_DAY_IN_MILLIS 
    + " instanceCounter=" + instanceCounter); 
} 

// an instance initialization block 
// instance blocks are executed each time a class instance is created, 
// after the parent constructor, but before any own constructors (as remarked by Ahmed Hegazy) 
{ 
    StaticDemo.instanceCounter++; 
    System.out.println("instanceCounter=" + instanceCounter); 
} 

public static void main(String[] args) { 
    System.out.println("Starting StaticDemo"); 
    new StaticDemo(); 
    new StaticDemo(); 
    new StaticDemo(); 
} 

static { 
    System.out.println("Class StaticDemo loaded"); 
} 

} 

출력 : '시작 StaticDemo는'출력의 첫 행으로 표시하지 않는 방법

Class StaticDemo loading... 
ONE_DAY_IN_MILLIS=86400000 instanceCounter=0 
Class StaticDemo loaded 
Starting StaticDemo 
instanceCounter=1 
instanceCounter=2 
instanceCounter=3 

알 수 있습니다. 그 이유는 클래스가 에로드되어보다 먼저 실행되어야하므로 모든 정적 필드와 블록이 순서대로 처리된다는 의미입니다.

+0

멋진 설명 @Adriaan – tez

+0

글쎄, 많이 고마워요! –

+0

놀라운. 이것은 올바른 대답이어야합니다! – Antonio

0

로딩은 런타임 작업입니다. 모든 것은 런타임에로드됩니다.

2

정적 필드는 클래스가로드 될 때로드됩니다. 일반적으로 클래스의 파일 객체가 만들어 지지만, 클래스가 다른 방법으로 사용되면 더 빠를 수 있습니다.

정적 초기화 프로그램은 스레드로부터 안전하므로 여러 스레드에서 클래스에 안전하게 액세스 할 수 있습니다. 이것은 잠금을 사용하지 않고도 스레드 세이프 싱글 톤을 만드는 방법으로 유용합니다.

참고 : 클래스 로더를 여러 개 사용하는 경우 클래스를 두 번 이상로드 할 수 있습니다 (정적 정적 블록 실행). 일반적으로 동일한 클래스를 여러 클래스 로더에로드하는 것은 혼란스럽고 피할 수 있지만 지원되고 작동합니다.

0

java ClassName을 입력하면 클래스가 정적 변수를 사용하여 JVM에로드되므로 객체가 필요하지 않습니다.

여기서 인스턴스 변수는 객체 생성시 JVM에 의해로드됩니다.

관련 문제