反射类的方法(其中main方法比较特殊)
package reflet; import java.util.List; public class person { public String name="hahaah"; public void aa1()//方法 { System.out.println("aa1"); } public void aa1(String name,int password) { System.out.println(name+":"+password); } public Class[] aa1(String name,int[] password) { return new Class[]{String.class}; } private static void aa1(int num) { System.out.println(num); } public static void main(String[] args) { System.out.println("main!!!"); } }
package reflet; import java.lang.reflect.Method; import org.junit.Test; public class demo2 { //反射类的方法:public void aa1(){} @Test public void test1() throws Exception { person p=new person(); Class clazz=Class.forName("reflet.person");//加载类 Method method=clazz.getMethod("aa1", null); method.invoke(p,null);//让方法跑起来,得有p对象才能跑 } //反射类的方法:public void aa1(String name,int password) @Test public void test2() throws Exception { person p=new person(); Class clazz=Class.forName("reflet.person");//加载类 Method method=clazz.getMethod("aa1", String.class,int.class); method.invoke(p,"hemaoyun",23);//让方法跑起来,得有p对象才能跑 } //反射类的方法:public Class[] aa1(String name,int[] password) @Test public void test3() throws Exception { person p=new person(); Class clazz=Class.forName("reflet.person");//加载类 Method method=clazz.getMethod("aa1", String.class,int[].class); Class ca[]=(Class[]) method.invoke(p,"hemaoyun",new int[]{1,2,4,5});//让方法跑起来,得有p对象才能跑 System.out.println(ca[0]); } //反射类的方法:private static void aa1(int num) @Test public void test4() throws Exception { person p=new person(); Class clazz=Class.forName("reflet.person");//加载类 Method method=clazz.getDeclaredMethod("aa1", int.class); method.setAccessible(true); method.invoke(p,57);//让方法跑起来,得有p对象才能跑 } //反射类的方法:public static void main(String[] args) @Test public void test5() throws Exception { person p=new person(); Class clazz=Class.forName("reflet.person");//加载类 Method method=clazz.getDeclaredMethod("main", String[].class); method.invoke(null,(Object)new String[]{"we","you"}); //记住,反射类调用main方法时,前面加上object强转下,这是版本升级兼容性问题。 //因为main方法是静态的,所以不需要对象p } }