Home  >  Article  >  Java  >  What is the role of java's reflection mechanism?

What is the role of java's reflection mechanism?

王林
王林forward
2023-04-19 08:55:021831browse

1. Function description

(1) Through reflection, the program code can access the internal information loaded in the JVM.

(2) Obtain the member variable information of the loaded class.

(3) Obtain the method of loading class.

(4) Obtain the structure method information of the loading class.

2. Instance

During the running process, the member variables and methods of a class are judged.

Class ownerClass = owner.getClass():得到该对象的Class。
 
Field field = ownerClass.getField(fieldName):通过Class得到类声明的属性。
 
Object property = field.get(owner):
通过对象得到该属性的实例,如果这个属性是非公有的,这里会报IllegalAccessException。
在运行时调用一个对象的方法:
Method method = ownerClass.getMethod(methodName, argsClass):
通过Method名和参数的Class数组得到要执行的Method。
 
method.invoke(owner, args):执行该Method,invoke方法的参数是执行这个方法的对象,和参数数组。
返回值是Object,也既是该方法的返回值。

The above is the detailed content of What is the role of java's reflection mechanism?. 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