Find out what methods are defined in a class, which is a very valuable and very basic reflection usage. The following code implements this usage:
Import java.lang.reflect.*;PublicClass Method1 {PrivateIntF1 (Object p,int x) throws NullPointerException {if (p = =NullThrowNew NullPointerException ();return x; }PublicStaticvoidMain (String args[]) {try {Class cls = Class.forName ("Method1"); Method methlist[] = Cls.getdeclaredmethods ();for (int i =0; i < methlist.length; i++) {Method m = methlist[i]; System.Out.println ("name =" + M.getname ()); System.Out.println ("Decl class =" + M.getdeclaringclass ()); Class pvec[] = M.getparametertypes ();for (int j = 0; j < Pvec.length; j+ +) System. out.println ( "param #" + j + "+ pvec[ J]); Class evec[] = M.getexceptiontypes (); for (int j = 0; j < Evec.length; j+ +) System. out.println ( "exc #" + j + "+ Evec[j] ); System. out.println ( "return type =" + M.getreturntype ()); System. out.println ( "-----");}} catch (Throwable e) {System.err.println (e);}}
This program first obtains the description of the Method1 class, and then calls Getdeclaredmethods to obtain a series of method objects that describe each of the methods defined in the class, including the public method, the protected method, the package method, and Private methods and so on. If you use GetMethods in your program instead of Getdeclaredmethods, you can also get information about the various methods that are inherited.
After you have obtained a list of method objects, it is not difficult to display the parameter types, exception types, and return value types of these methods. These types are basic or class types, and can be given sequentially by the objects that describe the class.
The results of the output are as follows:
class = class method1param #0 class java.lang.Objectparam #1 intexc #0 class java.lang.NullPointerExceptionreturn type = int-----name = maindecl class = class method1param #0 class [Ljava.lang.String;return type = void
Find the method of the class