Java - reflection mechanism

In many sources of Java, the reflection mechanism of Java is widely used. Therefore, here is a summary record of Java's reflection.
Java's reflection mechanism means that in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties. The java reflection mechanism enables the java language to know the information of classes and objects that are not known at compile time at runtime, and can call corresponding methods and modify attribute values.
1. Get the class of the object

Class clazz = Object.getClass();

2. Get class information

String className = clazz.getName();
Method[] methods = clazz.getDeclaredMethods(); //方法
Field[] fields = clazz.getFields(); //字段

3. Build Objects

Class.forName("className ").newInstance();

4. Dynamic execution method

Method mthod = clazz.getDeclaredMethod("add", int.class,int.class);
mthod.invoke(mthod, 1,2);

5. Dynamic Operation Properties

Field field = clazz.getDeclaredField("name");
field.get(this);
field.set(this, new Object());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325564348&siteId=291194637