我學到的東西是新建對象是強制性的。所以,這行代碼(來自java swing)是如何工作的?下面這行代碼如何在沒有new運算符的情況下創建對象?
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
我學到的東西是新建對象是強制性的。所以,這行代碼(來自java swing)是如何工作的?下面這行代碼如何在沒有new運算符的情況下創建對象?
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
這是因爲static
實施getLocalGraphicsEnvironment
方法,它返回一個GraphicsEnvironment
型的。從class itself, definition爲 -
/**
* Returns the local <code>GraphicsEnvironment</code>.
* @return the local <code>GraphicsEnvironment</code>
*/
public static synchronized GraphicsEnvironment getLocalGraphicsEnvironment() {
if (localEnv == null) {
localEnv = createGE();
}
return localEnv;
}
其中localEnv
被聲明爲 -
private static GraphicsEnvironment localEnv;
下面是從createGE()
代碼:
private static GraphicsEnvironment createGE() {
GraphicsEnvironment ge;
String nm = AccessController.doPrivileged(new GetPropertyAction("java.awt.graphicsenv", null));
try {
// long t0 = System.currentTimeMillis();
Class<GraphicsEnvironment> geCls;
try {
// First we try if the bootclassloader finds the requested
// class. This way we can avoid to run in a privileged block.
geCls = (Class<GraphicsEnvironment>)Class.forName(nm);
} catch (ClassNotFoundException ex) {
// If the bootclassloader fails, we try again with the
// application classloader.
ClassLoader cl = ClassLoader.getSystemClassLoader();
geCls = (Class<GraphicsEnvironment>)Class.forName(nm, true, cl);
}
ge = geCls.newInstance();
// long t1 = System.currentTimeMillis();
// System.out.println("GE creation took " + (t1-t0)+ "ms.");
if (isHeadless()) {
ge = new HeadlessGraphicsEnvironment(ge);
}
} catch (ClassNotFoundException e) {
throw new Error("Could not find class: "+nm);
} catch (InstantiationException e) {
throw new Error("Could not instantiate Graphics Environment: "
+ nm);
} catch (IllegalAccessException e) {
throw new Error ("Could not access Graphics Environment: "
+ nm);
}
return ge;
}
雖然它從未真正直接調用new
創建一個對象,它使用反射爲您創建GraphicsEnvironment。在這種情況下,調用newInstance()
會創建一個您正在使用的類的新實例,除非您運行的是無頭的;在這一點上它是直接用new
關鍵字創建的。
再次感謝兄弟 – trotsky
它正在調用一個方法。該方法內的某些東西知道如何檢索或創建一個'GraphicsEnvironment'對象並將其返回給您。該方法負責如何製造物體;你並沒有創造它。 – khelwood
你不是_creating_對象;該功能是。 – SLaks
所以GraphicsEnvironment類必須有一個'static'修飾符,因爲只有靜態類的方法可以直接使用類名來調用。 – trotsky