假設我有一個帶有一些「Utils」類的Java項目,並且這些類只有static
方法和成員。靜態方法是否總是加載到內存中?
一旦我運行我的應用程序,那些方法和成員會自動加載到內存中嗎?或者只有當我沿着代碼調用類時纔會發生這種情況?
編輯:一些示例代碼來說明我的問題。
RandomUtils.java
public class RandomUtils {
private static Random rand = new Random();
public static int randInt(int min, int max) {
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
return rand.nextInt((max - min) + 1) + min;
}
}
MainClass.java
public class MainClass {
public static void main(String[] args) {
// Some other operations. Is my class already loaded here?
int randomNumber = RandomUtils.randInt(1,10); // Or is it only loaded here?
}
}
如果這個類有其他靜態成員和方法,如果只加載一次,我調用一個什麼他們,其他方法也加載?
Downvoter,你能解釋一下有什麼問題嗎? – Mauker
有關一般性討論,請參閱:http://javarevisited.blogspot.com/2012/07/when-class-loading-initialization-java-example.html – mhp