Reprinted from Concurrent Programming network –ifeve.com
Content index
Get Constructor Object
Constructor method parameters
Instantiating a class with a constructor object
Using the reflection mechanism of Java you can examine how a class is constructed, and you can create an object at run time. These functions are implemented through the Java.lang.reflect.Constructor class. This section describes the Java constructor object in depth.
Get Constructor Object
We can get an instance of the constructor class through the class object:
Class AClass = ...//Get class object constructor[] constructors = aclass.getconstructors ();
The returned constructor array contains each of the public-constructed methods declared.
If you know the method parameter type of the constructor method you want to access, you can get the specified constructor method using the following method, which returns the method parameter of the constructor method to string type:
Class AClass = ...//Get class object Constructor Constructor = aclass.getconstructor (new Class[]{string.class});
If no specified constructor method satisfies the matching method parameter, it is thrown: nosuchmethodexception.
Constructor method parameters
You can get the method parameter information for the specified construction method in the following ways:
Constructor Constructor = ...//Get Constructor object class[] parametertypes = Constructor.getparametertypes ();
Instantiating a class with a constructor object
You can instantiate a class by using the following method:
Constructor Constructor = MyObject.class.getConstructor (string.class); MyObject MyObject = (MyObject) constructor.newinstance ("Constructor-arg1");
The method parameter of the Constructor.newinstance () method is a mutable argument list, but you must provide an exact argument when you call the constructor method, where the formal participation argument must be one by one-corresponding. In this example, the constructor method requires a string parameter, so we must pass in a string parameter when calling the Newinstance method.
Original address Author: Jakob Jenkov Translator: Yevenhai ([email protected])
Java Reflection (iii): constructors