2014-06-05 4 views

답변

3

예, 기능상으로 같습니다.

There is an alternative to static blocks — you can write a private static method: 

class Whatever { 
    public static varType myVar = initializeClassVariable(); 

    private static varType initializeClassVariable() { 

     // initialization code goes here 
    } 
} 

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable. 
1

Java doc의 결과는 동일하다.

두 경우 모두 정적 변수는 클래스 로딩으로 초기화됩니다.

정적 메서드와 정적 클래스 블록은 서로 다른 두 가지입니다. static 메소드는 정적 클래스 블록이 클래스 로딩과 함께 자동으로 실행되는 곳에서 호출해야합니다.

0

먼저 정적 메서드를 선언하지 않았습니까? 당신은 실행 순서 알고 싶어 아마도 경우, # 2가 발생하는 경우 또는 완전히 독립적 인 인스턴스를 생성

1) constructors 

호출은 이제까지 당신이 호출 할 때 호출 모든

2)static methods 

에서 발생하는 경우에도 그것들은 # 1이 일어날 때, 또는 심지어 전혀 일어나지 않았을 때와 완전히 독립적입니다.

3)static blocks 

클래스가 초기화 될 때 호출됩니다 # 1 또는 # 2가 발생할 수 있습니다.

0

정적 초기화 프로그램과 정적 블록은 둘 다 클래스가 초기화 될 때 실행됩니다. 정적 블록은 초기화시에 간단한 할당으로 특성화 할 수없는 무언가를하기를 원하기 때문에 정적 블록이 존재하기 때문에 존재합니다 :

static final Logger log = Logger.getLogger(ThisClass.class); 
static final String PROPS_FILE = "/some/file.properties"; 
static final Properties gProps; 
static { 
    gProps = new Properties(); 
    try { 
     FileReader reader = new FileReader(PROPS_FILE); 
     try { 
      gProps.load(reader); 
     } finally { 
      reader.close(); 
     } 
    } catch (IOException e) { 
     throw new SomeException("Failed to load properties from " + PROPS_FILE, e); 
    } 
    log.info(ThisClass.class.getName() + " Loaded"); 
} 
관련 문제