下面是反射封装的代码,废话不多说直接看代码
package com.rongtai.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws Exception {
test();
}
public static void test() throws Exception {
A impl = new A();
Class<?> clazz = impl.getClass();
Method m = clazz.getMethod("print", getPeremeterClass(impl, "print"));
// 调用你要指定的方法 应该知道 参数的类型和数量
m.invoke(impl, "Hello", " world");
}
public static Class<?>[] getPeremeterClass(Object obj, String methodName)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> clazz = obj.getClass();
Method[] method = clazz.getDeclaredMethods();
for (Method m : method) {
System.out.println(m.getName());
/**
* 跳过非指定的方法
*/
if (!m.getName().equals(met