Home  >  Article  >  Java  >  How to create objects using java reflection

How to create objects using java reflection

WBOY
WBOYforward
2023-05-10 21:55:043237browse

1. Use the newInstance() method of the Class object to create the object

(1) Obtain the Class object.

(2) Obtain the object by calling newInstance() of the obtained Class object. This method will return an object of Object type, so forced rotation is required

2. Through the Constructor class newInstance () Get

(1) Get a Class instance

(2) Call the getConstructor() method in Class to get the Constructor object

(3) Call The newInstance() method of Constructor obtains the instance of the class

3, instance

Class clazz=Dog.class;
Constructor constructor=clazz.getConstructor(String.class,int.class});
Dog dog=(Dog) constructor.newInstance("xiaohei",3});
System.out.println(dog.name+" "+dog.age);

In the second line of the program, we call the getConstructor method of the Class object, and then in the parameter list Pass in String and int, because the parameter list of our parameterized constructor is specified in this way, and now we have obtained the parameterized constructor of the Dog class defined earlier.

In the third line, we call the newInstance method through the obtained Constructor object, and then pass in the parameter list of type Object in the method, because our parameterized constructor requires these values, so that it can be passed through reflection The method creates objects that only have parameterized constructors.

The above is the detailed content of How to create objects using java reflection. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete