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

How to create objects using java reflection

WBOY
Release: 2023-05-10 21:55:04
forward
3256 people have browsed it

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);
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template