如果没有new运算符,以下代码行如何创建对象?

时间:2017-01-25 21:32:40

标签: java swing

我学到的是创建一个对象必须使用new。那么,这行代码(来自java swing)是如何工作的?

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

2 个答案:

答案 0 :(得分:0)

这是因为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;

答案 1 :(得分:0)

以下是dataType: 'json'的代码:

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; } 来创建对象,但它确实使用反射来为您创建GraphicsEnvironment。在这种情况下,对new的调用会创建您正在使用的类的新实例,除非您正在运行Headless;此时,它是使用newInstance()关键字直接创建的。