繁体   English   中英

使用通用Java类时的InstantiationException

[英]InstantiationException when using a generic java class

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

实体:

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

我得到以下InstantiationException:

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)

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

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

只要使这些内部类成为顶级类,您的示例就可以按预期工作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM