Home  >  Article  >  Java  >  What are the main functions provided by the Java reflection mechanism?

What are the main functions provided by the Java reflection mechanism?

青灯夜游
青灯夜游Original
2020-09-28 17:14:0710730browse

The main functions provided by the Java reflection mechanism are: 1. Determine the class to which any object belongs at runtime; 2. Construct an object of any class at runtime; 3. Determine the attributes of any class at runtime. member variables and methods; 4. Call the method of any object at runtime; 5. Generate a dynamic proxy.

What are the main functions provided by the Java reflection mechanism?

The main functions provided by JAVA’s reflection mechanism are:

1. Determine the ownership of any object at runtime Class;

2. Construct an object of any class at runtime;

3. Determine the member variables and methods of any class at runtime;

4. Call the method of any object at runtime;

5. Generate a dynamic proxy;

Get the class to which the object belongs:

Class ownerClass = owner.getClass()

Construct a class at runtime Object:

Class newoneClass = Class.forName(className):第一步,得到要构造的实例的Class。

Constructor cons = newoneClass.getConstructor(argsClass):得到构造器。

cons.newInstance(args):新建实例。

Determine the member variables and methods of a class at runtime:

Class ownerClass = owner.getClass(): Get the Class of the object.

Field field = ownerClass.getField(fieldName): Get the attributes declared by the class through Class.

Object property = field.get(owner): Get the instance of the property through the object. If this property is non-public, an IllegalAccessException will be reported here.

Call an object's method at runtime:

Method method = ownerClass.getMethod(methodName, argsClass): Get the Method to be executed through the Method name and the Class array of parameters.

method.invoke(owner, args): Execute the Method. The parameters of the invoke method are the object to execute this method and the parameter array.
The return value is Object, which is also the return value of this method.

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of What are the main functions provided by the Java reflection mechanism?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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