Mark Mamdouh
Mark Mamdouh

Reputation: 169

Create an object from a class name

I have a String array that contains my classes names , and i want that every loop i create an object from the class name in the array to get methods from it,

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
}

i have tried this method

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[] {  });

but it gives me that error

enter image description here

Upvotes: 1

Views: 145

Answers (1)

chengpohi
chengpohi

Reputation: 14227

You need to throw NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException in your method, like:

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

and There is another issue existing in your code.

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

Your constructor set String as parameter, but when you call newInstance, you are setting an empty Object array as parameter. Maybe:

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

Upvotes: 1

Related Questions