samedi 7 janvier 2017

Class.newInstance for anonymous java classes [duplicate]

This question already has an answer here:

I have a class which spawn instances of itself, which adapts to its new extended class (if extended)

/// Class name is obviously for fun =)
public 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);
        }
    }

    ...
}

This works fine and all.... until someone tries to use it as an anonymous class.

public 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();

Unfortunately (or fortunately?) this fails with the following.

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

So how does one spawn a new instance of an anonymous class in Java?





Aucun commentaire:

Enregistrer un commentaire