@Test public void methodtest() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { Class<User> userClass = User.class; User user = userClass.newInstance(); //设置调用方法名和重载方法的形参类型 Method show = userClass.getDeclaredMethod("show", String.class); //调用private修饰需要设置权限 show.setAccessible(true); //invoke调用方法,设置对象和形参,invoke接收的返回值即为show方法的返回值 Object invoke = show.invoke(user, "小明"); System.out.println(invoke); System.out.println("**************************************"); Method staticmethod = userClass.getDeclaredMethod("staticmethod"); staticmethod.setAccessible(true); //一下三个都可以因为静态方法不需要对象来指明,所以也可以写null Object invoke1 = staticmethod.invoke(User.class); Object invoke2 = staticmethod.invoke(user); Object invoke3 = staticmethod.invoke(null); } } //user中的方法截取 private String show(String name){ System.out.println("my name is"+name); return name; } private int show(int age){ System.out.println("my year old is"+age); return age; } private static void staticmethod(){ System.out.println("此方法为静态方法且没有返回值"); }