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