in general, create an object by using the following methods
Rectangle r = new Rectangle ();
But if you are developing a development tools, you may not know the class to generate the object before you run it.
so you want to create objects like the following:
String ClassName;
//... load className from the user interface
Object o = new (ClassName); wrong!
But the above is wrong.
the correct way is to use the reflection property of a class:
1) Using no-argument Constructors
For example:
Class classdefinition = Class.forName (className);//Specify the Run-time instance of the class
object = Classdefinition.newinstance ();//The parameterless constructor is invoked to generate an instance of the specified class.
2) Using constructors that Have Arguments
This technique will use the following steps:
A, create a class object
B, create a constructor object, GetConstructor (class[] params) method, which is an array of classes appropriate to the construction method.
C, the Newinstance method is invoked on the constructor object to generate an object, which is equipped with an object array and this constructor method.
For example:
import java.lang.reflect.*;
import java.awt.*;
class Sampleinstance {
public static void Main (string[] args) {
Rectangle Rectangle;
Class rectangledefinition;
class[] Intargsclass = new class[] {int.class, int.class};
c. Call the Field.set (Object,withparam) method (XXX is int,float, if the object is omitted; object is an instance, Withparam refers to a field that matches this field.)
B. Create a Method object Method,getmethod (String methodname,class[]) method
C. Method Object, Method.invoke (object,object[]), two parameters, the first refers to the object to which the method is invoked, and the second is the list of Value objects passed.
the "sample program" that follows shows and you to invoke a method dynamically. The program retrieves the "method object" String.Concat method and then uses invoke to concatenate two String object S.
//
import java.lang.reflect.*;
class Sampleinvoke {
public static void Main (string[] args) {
String FirstWord = "Hello"; Specify an instance of the class
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.