Find the method of the class

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.