“Using java.lang.reflect” will answer all your questions. First fetch the Class object using Class.forName(), and then:
If I want to instantiate a class that I retrieved with
forName(), I have to first ask it for ajava.lang.reflect.Constructorobject representing the constructor I want, and then ask thatConstructorto make a new object. The methodgetConstructor(Class[] parameterTypes)inClasswill retrieve aConstructor; I can then use thatConstructorby calling its methodnewInstance(Object[] parameters):Class myClass = Class.forName("MyClass"); Class[] types = {Double.TYPE, this.getClass()}; Constructor constructor = myClass.getConstructor(types); Object[] parameters = {new Double(0), this}; Object instanceOfMyClass = constructor.newInstance(parameters);
There is a newInstance() method on Class that might seem to do what you want. Do not use it. It silently converts checked exceptions to unchecked exceptions.
Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The
Constructor.newInstancemethod avoids this problem by wrapping any exception thrown by the constructor in a (checked)InvocationTargetException.