Home  >  Article  >  Java  >  How to create java reflection mode

How to create java reflection mode

WBOY
WBOYforward
2023-04-19 10:58:021205browse

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();

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);

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!

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