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

Analysis of object instances generated by java reflection

WBOY
Release: 2023-05-01 21:25:05
forward
1051 people have browsed it

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

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!

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