匿名java类的Class.newInstance

时间:2017-01-07 13:29:30

标签: java reflection

我有一个产生自身实例的类,它适应新的扩展类(如果扩展)

/// Class name is obviously for fun =)
public class HiveMind {

    /// It does have a public proper constructor
    public HiveMind() {
        doSomething();
    }

    /// With great ambition
    public void doSomething() {
        // Should we Take over the world?
    }
    ...

    /// Spawn and instance of the current class
    public final HiveMind spawnInstance() throws ServletException {
        try {
            Class<? extends HiveMind> instanceClass = this.getClass();
            HiveMind ret = instanceClass.newInstance();
            // Does some stuff here
            // And for those who says "newInstance" is evil
            // This is an evil HiveMind then D=
            return ret;
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    ...
}

这很好用,直到有人试图将它用作匿名类。

HiveMind nextGeneration = new HiveMind() {
    // New generation new mind set.
    public void doSomething() {
        this.enslaveHumans(); // Yes we should
    }
};

// Time to spread the hive mind!
nextGeneration.spawnInstance();

不幸的是(或者幸运的是?)以下内容失败了。

java.lang.NoSuchMethodException: HiveMind_test$1.&lt;init&gt;()
    java.lang.Class.getConstructor0(Class.java:3082)
    java.lang.Class.newInstance(Class.java:412)
    HiveMind.spawnInstance(HiveMind.java:383)
    ....

那么如何在Java中生成匿名类的新实例?

为了澄清目的,不要在Anonymous类之外重用变量,以避免状态捕获。

PS:Dynamic construction of anonymous class confusion,没有提供我需要的答案。然而,它确实解释了为什么目前不起作用的原因。

0 个答案:

没有答案