Reflection Recognition _04_ Reflection call class method

Source: Internet
Author: User

Package 1:

Package Reflectionmethod;public class Reflectionmethod {String str1= "str1";p ublic void OutStr1 () {System.out.println (" Output the first string: "+STR1);} public void OutStr2 (string str2) {System.out.println ("outputs a second string:" +STR2);} public void OutStr3 (string str3,string str4) {System.out.println ("output of the third string:" +STR3); SYSTEM.OUT.PRINTLN ("Output of the fourth string:" +STR4);}}

  

Package 2:

Package Reflectionmethod;import Java.lang.reflect.method;public class Reflectionachieve {public static void main ( String[] args) throws Exception {Reflectionmethod rp=new reflectionmethod (); Usemethod (RP);} public static void Usemethod (Object obj) throws exception{/* calls Method 1 without Parameters */method Out1=obj.getclass (). GetMethod ("OutStr1 ");//Get class through the object, Get class method Out1.invoke (obj) through the class,//pass in the object, and use method, if it is static method, can pass in null/* call Method 2, with 1 parameters */method Out2=obj.getclass (). GetMethod ("OutStr2", string.class);//Get class by object, pass in method parameter type, get class method Out2.invoke (obj, "str2") through class, pass in object, pass in variable, and use method/* To call Method 3, With multiple parameters */method Out3=obj.getclass (). GetMethod ("OutStr3", string.class,string.class);//Get class by object, pass in multiple parameter types, Get the class method through the class Out3.invoke (obj, "Str3", "STR4");//Pass in the object, pass in multiple variables,-use the method}}

  

Reflection Recognition _04_ Reflection call class method

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.