3

B-Object を作成できませんが、なぜですか?

public class AFactory {

    public int currentRange;

    private abstract class A {
        protected final Object range = currentRange;

        public int congreteRange = 28;
    }

    public class B extends A {
        public int congreteRange = 42;
    }

    synchronized A createNew(Class<? extends A> clazz) throws Exception {
        // EDIT: there is accessible default constructor
        currentRange = clazz.newInstance().congreteRange;
        return clazz.newInstance();
    }

    public static void main(String[] args) throws Exception {
        AFactory factory = new AFactory();
        System.out.println(factory.createNew(B.class).range);
    }
}

例外は次のとおりです。

Exception in thread "main" java.lang.InstantiationException: AFactory$B
at java.lang.Class.newInstance0(Class.java:357)
at java.lang.Class.newInstance(Class.java:325)
at AFactory.createNew(AFactory.java:15)
at AFactory.main(AFactory.java:21)
4

3 に答える 3

-1

クラスと変数を静的に変更します。

public class AFactory {

public static int currentRange;

private static abstract class A {
    protected final Object range = currentRange;
}

public static class B extends A {

    public int congreteRange = 42;
}

synchronized A createNew(Class<? extends B> clazz) throws Exception {

    currentRange = clazz.newInstance().congreteRange;
    return clazz.newInstance();
}

public static void main(String[] args) throws Exception {
    AFactory factory = new AFactory();
    System.out.println(factory.createNew(B.class).range);
}
}

出力は42です。

于 2013-10-02T12:52:17.910 に答える