2015-10-05 23 views
0

我想创建一个包含实体的模拟。可以有两种实体,复杂和简单的实体。当我实例化一个简单的仿真时,我希望简单的实体被实例化,并且当我实例化一个复杂的仿真时,我希望实例化复杂的实体。当使用通用Java类时的InstantiationException

实体:

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

我得到以下Instantiat ionException:

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) 

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

+1

例外要告诉你什么是错的。发布堆栈跟踪。 –

+0

我添加了堆栈跟踪 – marczoid

+0

您正在使用不删除的泛型类,泛型类型现在不是实际的类型。 – 2015-10-05 16:27:35

回答

2

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

只要让这些内部类成为顶级类,您的示例应该按预期工作。

如果你真的想/需要使用反射来初始化非静态内部类,在这里看到:How to instantiate inner class with reflection in Java?

+0

这也不是这种情况 – 2015-10-05 16:32:03

+0

是的,这是nikpon的情况!感谢Luiggi,您的解决方案解决了我的问题。 – marczoid

+0

@nikpon是的。看看堆栈跟踪。 –

相关问题