Java record-84-Reflection API example

Source: Internet
Author: User

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 );}}

 

 

Related Article

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: info-contact@alibabacloud.com 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.