In-depth understanding of Java reflection method to create code

When talking about examples, many people still can't explain why this concept is. In fact, an instance is a specific object, like the classes and arrays we learned before, you can create instances. Reflection is also a relatively abstract concept, so we can instantiate it. The following is a brief understanding of the examples, and then bring the non-parameter and parameterized reflection instance instantiation methods respectively.

1. Example description

New An object is an instance. You can call the new object an instance. To put it bluntly, it is the "thing" that is new. You can also call it an object or an instance. The object and the instance are equivalent from this point of view. of.

2. Create an instance of the null parameter

Use the newInstance() method of the Class object to create an instance of the corresponding class of the Class object.

//Original: When new, first look for the bytecode file of the new class according to the name of the class, and load it into the memory.

//And create the bytecode file object, and then create the 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);

Content expansion:

Definition of
reflection The reflection mechanism refers to the ability of a program to obtain its own information while it is running. In Java, as long as the name of the class is given, all the attributes and methods of the class can be obtained through the reflection mechanism.

The role of reflection

  • Judge the class to which any object belongs at runtime.
  • Judge the member variables and methods of any class at runtime.
  • Arbitrarily call a method of an object at runtime
  • Construct an object of any class at runtime

The latest high-frequency interview questions collected in 2021 (all organized into documents), there are a lot of dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations. There are also detailed learning plans and interviews. Question sorting, etc. For those who need to obtain these contents, please add Q like: 11604713672

Guess you like

Origin blog.csdn.net/weixin_51495453/article/details/114449040