Java reflection get and call methods

Get methods from class: public method [] getmethods()// Get all public methods including itself and inherited (implemented) - method does not support generic < >, that is, it is not followed by < > public method [] getdeclaredmethods()// Get all its own methods (private, public, protected, independent of access rights), excluding inherited methods in jdk1 After 8, the methods that can directly obtain private properties do not need to set permissions, but are limited to getdeclaredmethod methods. Permissions still need to be set for method methods. public Method[] getmethod(String methodName,Class
...parameterTypes);// Indicates to obtain a specified public method, including inherited parameters: methodname: indicates the name of the obtained method parametertypes: indicates the class type of the parameters of the obtained method public method [] getdeclaredmethod (string methodname, class < T >... Parametertypes)// Means to obtain a specified method (private, protected, public, independent of access rights) in this class, excluding inherited methods

For method calls with multiple parameters: the parametertypes followed by getdeclaraedmethod can be understood as formal parameters of class type. The assignment of multiple parameters can be assigned by calling invoke. It is best to wrap them in new object [] {}.

Call static method

There are two ways to call static methods:

1. Because static methods are common to all instance objects, you can create an arbitrary object of this class and call staticmethod through this object invoke(clz.newInstance());// Staticmethod has no parameters, so the parameter list type is not filled in

2. If the underlying method is static, you can ignore the specified obj parameter and set the obj parameter to null to staticmethod invoke(null);

More relevant:

1: Reflection concept

You can get the member variables and methods of a class through the class class and call them.

2: Obtain methods, variables and construction methods through reflection

3: Call the method defined by the class through reflection

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>