You can obtain Constructor
class from the Class
object like this:
Class myClass = ... // get a class object
Constructor[] constructors = myClass.getConstructors();
Where the constructors
variable will have one Constructor
instance for each public constructor declared in the class.
If you know the precise parameter types of the constructor you want to access, you can filter the specific constructor. The next example returns the public constructor of the given class which takes a Integer
as parameter:
Class myClass = ... // get a class object
Constructor constructor = myClass.getConstructor(new Class[]{Integer.class});
If no constructor matches the given constructor arguments a NoSuchMethodException
is thrown.
Class myClass = MyObj.class // get a class object
Constructor constructor = myClass.getConstructor(Integer.class);
MyObj myObj = (MyObj) constructor.newInstance(Integer.valueOf(123));