PackageReflet;Importjava.util.List; Public classPerson { PublicString name= "Hahaah"; Public voidAa1 ()//Method{System.out.println ("Aa1"); } Public voidAa1 (String name,intpassword) {SYSTEM.OUT.PRINTLN (name+":"+password); } PublicClass[] Aa1 (String name,int[] password) { return NewClass[]{string.class}; } Private Static voidAa1 (intnum) {System.out.println (num); } Public Static voidMain (string[] args) {System.out.println ("Main!!!"); }}
PackageReflet;ImportJava.lang.reflect.Method;Importorg.junit.Test; Public classDemo2 {//method of Reflection class: public void Aa1 () {}@Test Public voidTest1 ()throwsException {person P=NewPerson (); Class Clazz=class.forname ("Reflet.person");//Load ClassMethod Method=clazz.getmethod ("Aa1",NULL); Method.invoke (P,NULL);//let the method run, you have to have a P object to run . } //method of Reflection class: public void Aa1 (String name,int password)@Test Public voidTest2 ()throwsException {person P=NewPerson (); Class Clazz=class.forname ("Reflet.person");//Load ClassMethod Method=clazz.getmethod ("Aa1", String.class,int.class); Method.invoke (P,"Hemaoyun", 23);//let the method run, you have to have a P object to run . } //method of Reflection class: public class[] Aa1 (String name,int[] password)@Test Public voidTest3 ()throwsException {person P=NewPerson (); Class Clazz=class.forname ("Reflet.person");//Load ClassMethod Method=clazz.getmethod ("Aa1", String.class,int[].class); Class ca[]= (class[]) Method.invoke (p, "Hemaoyun",New int[]{1,2,4,5}];//let the method run, you have to have a P object to run .System.out.println (ca[0]); } //method of Reflection class: private static void Aa1 (int num)@Test Public voidTest4 ()throwsException {person P=NewPerson (); Class Clazz=class.forname ("Reflet.person");//Load ClassMethod Method=clazz.getdeclaredmethod ("Aa1",int.class); Method.setaccessible (true); Method.invoke (P,57);//let the method run, you have to have a P object to run . } //method of Reflection class: public static void Main (string[] args)@Test Public voidTEST5 ()throwsException {person P=NewPerson (); Class Clazz=class.forname ("Reflet.person");//Load ClassMethod Method=clazz.getdeclaredmethod ("main", string[].class); Method.invoke (NULL, (Object)Newstring[]{"We", "You"}); //Remember, the reflection class calls the Main method, preceded by the object strong, which is the version upgrade compatibility issue. //because the main method is static, you do not need the object P }}
Methods of reflection classes (where the main method is more special)