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

What is the role of java's reflection mechanism?

王林
Release: 2023-04-19 08:55:02
forward
1897 people have browsed it

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,也既是该方法的返回值。
Copy after login

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!

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