47

for example:

public class Test {

    public static void main(String[] args) throws Exception {
        Car c= (Car) Class.forName("Car").newInstance();
        System.out.println(c.getName());
    }
}

class Car {
    String name = "Default Car";
    String getName(){return this.name;}
}

clear code.

But, if I add constructor with params, some like this:

public Car(String name)
{this.name = name;}

I see: java.lang.InstantiationException

So, no I don't know, how pass constructor with params.

Please, help.

user471011
  • 7,104
  • 17
  • 69
  • 97

2 Answers2

94

You need to say which constructor you want to use a pass it arguments.

Car c = Car.class.getConstructor(String.class).newInstance("Lightning McQueen");
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
8

If you are handling super / subclasses, or for whatever reason don't know exactly what Class is to be instantiated, the forName() method will be required also:

(ClassName) Class.forName([name_of_the_class])
      .getConstructor([Type]).newInstance([Constructor Argument]);

This assumes name_of_the_class is a passed variable. Also, if the class is in a package, even if that package has been imported, you still have to explicitly stipulate the package in forName() (I think, I'm new to all this).

Class.forName([name_of_package].[name_of_class])
C Dawson
  • 101
  • 1
  • 6