Home  >  Article  >  Java  >  Analysis of object instances generated by java reflection

Analysis of object instances generated by java reflection

WBOY
WBOYforward
2023-05-01 21:25:051001browse

1. Two generation methods

Use the newInstance() method of the Class object to create an instance of the corresponding class of the Class (this method requires that the corresponding class of the Class has a default structure).

Use the Class object to obtain the specified Constructor object, and then call the newInstance() method of the Constructor object to make an example of the class corresponding to the Class object (this method can select the specified constructor to make an example).

2. Instance

class Person {
 
    private String name;
 
    private Integer age;
 
    public Person() {
        this.name = "system";
        this.age = 99;
    }
 
    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
 
    public Integer getAge() {
        return age;
    }
 
    public String getName() {
        return name;
    }
 
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
 
 
public class Test {
 
    public static void main(String[] args) throws Exception {
        Class<Person> pClass = Person.class;
        // 通过第1种方式创建对象
        Person p = pClass.newInstance();
        System.out.println(p);
        // 通过第2种方式创建对象
        Constructor<Person> constructor = pClass.getDeclaredConstructor(
                                                    String.class, Integer.class);
        Person person2 = constructor.newInstance("zhangsan",20);
        System.out.println(person2);
    }
}

Objects can be created through configuration files containing key-value pairs. After reading the key-value pairs in the configuration file, the program can use the key-value pairs to create a "string-object" object pool, and then access these objects through strings.

The above is the detailed content of Analysis of object instances generated by 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