0

我想创建一个包含实体的模拟。可以有两种实体,复杂的和简单的。当我实例化一个简单的模拟时,我希望实例化一个简单的实体,而当我实例化一个复杂的模拟时,我希望实例化一个复杂的实体。

实体:

class ComplexEntity extends Entity {
    public ComplexEntity(){}
}

class SimpleEntity extends Entity  {
    public SimpleEntity(){}
}

class Entity {
    public Entity(){}
}

模拟:

class ComplexSimulation extends Simulation<ComplexEntity>
{

    public ComplexSimulation() throws InstantiationException, IllegalAccessException {
        super(ComplexEntity.class);
    }

}

class SimpleSimulation extends Simulation<SimpleEntity>
{
    public SimpleSimulation() throws InstantiationException, IllegalAccessException
    {
        super(SimpleEntity.class);
    }
}

class Simulation<E extends Entity> {
    protected final E entity;

    public Simulation(Class<E> class1) throws InstantiationException, IllegalAccessException 
    {
        entity = class1.newInstance();
    }
}

问题是当我尝试构建一个 ComplexSimulation 时:

ComplexSimulation c = new ComplexSimulation();

我得到以下实例化异常:

java.lang.InstantiationException: test.Test$ComplexEntity
at java.lang.Class.newInstance(Unknown Source)
at test.Test$Simulation.<init>(Test.java:55)
at test.Test$ComplexSimulation.<init>(Test.java:37)
at test.Test.go(Test.java:12)
at test.Test.main(Test.java:6)
Caused by: java.lang.NoSuchMethodException: test.Test$ComplexEntity.<init>()
at java.lang.Class.getConstructor0(Unknown Source)

零参数构造函数不可能是问题,因为我的实体有它们......有人知道问题可能是什么吗?

4

1 回答 1

3

问题是您正在使用内部类。如果没有外部类的实例,您不能创建内部类的实例,即使您调用Class<InnerClass>.newInstance().

只需将这些内部类设为顶级类,您的示例就应该按预期工作。

如果您真的想要/需要使用反射来初始化非静态内部类,请参见此处:如何在 Java 中使用反射来实例化内部类?

于 2015-10-05T16:29:25.907 回答