Through java. Lang. Reflect. method, we can access and call class methods at runtime.
If you know the method signature, you can directly retrieve the specified method:
Package Tao. xiao. action; import Java. lang. reflect. method; public class A implements it1 {public void F1 () {} public void F1 (string s) {} Public String F2 (int x) {return "XXX ";}; public static void main (string [] ARGs) throws classnotfoundexception, securityexception, nosuchmethodexception {class myclass = Class. forname ("Tao. xiao. action. A "); method [] Methods = myclass. getmethods (); // obtain all method M1 = myclass. getmethod ("f1", null); // if the function does not have a parameter, pass in nullmethod m2 = myclass. getmethod ("f1", new class [] {string. class}); Method m3 = myclass. getmethod ("F2", new class [] {Int. class}); system. out. println (M1); system. out. println (m2); system. out. println (m3 );}}
The running result is
public void tao.xiao.action.A.f1()public void tao.xiao.action.A.f1(java.lang.String)public java.lang.String tao.xiao.action.A.f2(int)
- Method parameters and return types
package tao.xiao.action;import java.lang.reflect.Method;public class A implements IT1 {public String[] f(int x, double[] y, String z) { return null; };public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException {Class myClass = Class.forName("tao.xiao.action.A");Method m = myClass.getMethod("f", new Class[]{int.class, double[].class, String.class});Class[] parameterTypes = m.getParameterTypes();for (Class parameterType : parameterTypes)System.out.println(parameterType);Class returnType = m.getReturnType();System.out.println(returnType);}}
The running result is:
intclass [Dclass java.lang.Stringclass [Ljava.lang.String;
- Invoking methods using method object
Package Tao. xiao. action; import Java. lang. reflect. invocationtargetexception; import Java. lang. reflect. method; public class A implements it1 {Public String [] F1 (int x, double [] Y, string Z) {system. out. println ("F1: x =" + x + ", y =" + Y + ", Z =" + Z); return New String [] {"AAA ", "BBB" };} public static void F2 (int x) {system. out. println ("F2: x =" + x);} public static void main (string [] ARGs) throws classnotfoundexception, securityexception, nosuchmethodexception, invocationtargetexception, illegalargumentexception, illegalaccessexception {method M1 =. class. getmethod ("f1", new class [] {Int. class, double []. class, String. class}); Method m2 =. class. getmethod ("F2", Int. class); A obja = new A (); string [] Ss = (string []) m1.invoke (obja, 100, new double [] {200,300,400}, "Haha "); for (string S: SS) system. out. println (s); m2.invoke (null, 330); // For the static method, the first parameter of invoke is null }}
The running result is
f1: x = 100, y = [D@61de33, z = hahaAAABBBf2: x = 330
Next chapter: Exploring Java reflection mechanism (getters and setters)