从类名创建对象

时间:2015-10-28 10:23:08

标签: java class object

我有一个包含我的类名的String数组,我想要每个循环我从数组中的类名创建一个对象来从中获取方法,

String[] namesArray = new String[3];
namesArray = {"Circle","Triangle","Ellipse"}
for(int i=0; i<namesArray.length(); i++){
    String s = namesArray[i];
    //here i want to create an object from s
}

我尝试过这种方法

String className = "TestReflection";
String fullPathOfTheClass = "eg.edu.alexu.csd.oop.draw." + className;
Class<?> clazz = Class.forName(fullPathOfTheClass);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] {  });

但它给了我那个错误

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要在方法中抛出NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException,例如:

void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException 

并且您的代码中存在另一个问题。

Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] {  });

您的构造函数将String设置为参数,但是当您调用newInstance时,您将设置一个空的Object数组作为参数。也许:

Object object = ctor.newInstance(new Object[] { "String Parameter" });