Home > Java > javaTutorial > body text

How to create java reflection mode

WBOY
Release: 2023-04-19 10:58:02
forward
1249 people have browsed it

1. Example description

new An object is an instance. You can call this new object an instance. To put it bluntly, it is the "thing" that comes out of this new. It is also called an object. Yes, you can call it an instance. Objects and instances are equivalent from this perspective.

2.Create an instance of with empty parameters. Use the newInstance() method of the Class object to create an instance of the corresponding class of the Class object.

//Original: When new, first find the bytecode file of the class based on the name of the new class, and load it into the memory,

//And create the bytecode file object, and then create a Person object corresponding to the byte file.

Person p = new Person();
 
//反射:找寻该类的名称,并加载进内存,并产生Class对象
//在产生类的对象
Strint className = "com.example.hgx.Person";
Class clazz = Class.forName(className);
Object obj = clazz.newInstance();
Copy after login

3. Create an instance with parameters. At this time, you need to obtain the specified Constructor object through the Class object, and then call the newInstance() method of the Constructor object to create an instance.

    class Person {
        public String name;
        private int age;
 
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
 
    }
 
//获取Person类带一个(String,int)参数的构造器
Strint className = "com.example.hgx.Person";
Class clazz = Class.forName(className);
Constructor constructor = clazz.getConstructor(String.class,int.class);
Copy after login

The above is the detailed content of How to create java reflection mode. 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