Java record-84-Reflection API example
The Reflection API uses two methods to obtain the Class: Class <?> Classtype = Class. forName ("java. lang. Object"); Class <?> ClassType = InvokeTester. class; 1. Obtain information about all methods of a class (runtime)
Public class DumpMethods {public static void main (String [] args) throws Exception {// basic function of Reflection API Class <?> Classtype = Class. forName ("java. lang. Object"); Method [] methods = classtype. getDeclaredMethods (); // obtain all methods in the specified Class, including private methods. (All methods at runtime) for (Method method: methods) {System. out. println (method );}}}
2. Call a specified method of a certain type through reflection
Public class InvokeTester {public int add (int a, int B) {return a + B;} public String echo (String message) {return "hello" + message ;} public static void main (String [] args) throws Exception {// general call method // InvokeTester test = new InvokeTester (); // System. out. println (test. add (3, 4); // System. out. println (test. echo ("welcome"); // Reflection call method Class <?> ClassType = InvokeTester. class; Object invokeTester = classType. newInstance (); // System. out. println (invokeTester instanceof InvokeTester); Method addMethod = classType. getMethod ("add", new Class [] {int. class, int. class}); Object result = addMethod. invoke (invokeTester, new Object [] {2, 3}); System. out. println (result); System. out. println ("-------------------------"); Method echoMethod = classType. getMethod ("echo", new Class [] {String. class}); Object result2 = echoMethod. invoke (invokeTester, new Object [] {"tom"}); System. out. println (result2 );}}