java invoke 的反射用法 及参数传递
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class test { public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { System.out.println("Hello World!"); Class<User> clas = User.class; Method m = clas.getMethod("method", String.class); m.invoke(null, "aa");//静态方法可省略对象,直接用null替代,或用clas m = clas.getDeclaredMethod("method", int.class);//非public方法要用declared获取 m.setAccessible(true);//非public方法需要设置为可访问 m.invoke(clas.newInstance(), 1);//非静态方法需要提供底层的类对象 } } class User { public static void method(String s) { System.out.println(s); } private void method(int i) { System.out.println(i); } }
不同元类的方式
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class test { public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { System.out.println("Hello World!"); User us = new User(); Method m = us.getClass().getMethod("method", String.class); m.invoke(us, "aa");//静态方法可省略对象,直接用null替代,或用clas m = us.getClass().getDeclaredMethod("method", int.class); m.setAccessible(true);//非public方法需要设置为可访问 m.invoke(us, 1);//非静态方法需要提供底层的类对象 } } class User { public static void method(String s) { System.out.println(s); } private void method(int i) { System.out.println(i); } }