日期:2014-05-17 浏览次数:20931 次
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class TheReflect { /** * @param args * @throws NoSuchMethodException * @throws SecurityException * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { // TODO Auto-generated method stub /** 详细的API使用方法参加JDK的doc文档中的java.lang.Class和java.lang.reflect.Method */ /* 相当于你在Spring的Context中获取bean对象 */ TheBeanClazz theBean = new TheBeanClazz(); /* 通过获取到bean对象得到该对象的类定义 */ Class clazz = theBean.getClass(); /* 通过上面得到的类定义对象clazz得到指定名称和参数类型列表的方法定义 */ Method m = clazz.getMethod("sayHello", String.class); /* * 在指定的对象(theBean)上调用符合上面方法定义的方法, * 并且制定方法的入口参数值列表(这个方法只有一个参数, * 如果是多个参数用逗号分隔) */ String msg = (String) m.invoke(theBean, "床上等你"); System.out.println("返回的结果 :" + msg); } } class TheBeanClazz { public String sayHello(String s) { System.out.println("Hello :" + s); return "Hello :" + s; } }
------解决方案--------------------
使用java的反射机制,查找此类中是否有这个方法,有的话使用反射机制实现调用这个方法
------解决方案--------------------
import java.lang.reflect.Method;
public class Test{
    
    /**
     * @param className 类名
     * @param methodName 方法名
     * @param param     方法参数
     * @param parameterType 方法参数类型
     * @throws Exception
     */
    private static void callMethod(String className,String methodName,Object[] param,Class...parameterType) throws Exception {
        Class cObj = Class.forName(className);
        Method m = cObj.getDeclaredMethod(methodName,parameterType);
        Object o = m.invoke(cObj.newInstance(),param);
    }
    
    public static void main(String[] args) throws Exception {
        callMethod("com.test.reflect.TestClass","method2",null);
        Object[] param = new Object[]{"测试数据"};
        callMethod("com.test.reflect.TestClass","method1",param,String.class);
    }
}
class TestClass{
    public void method2(){
        System.out.println("method2");
    }
    public void method1(String str){
        System.out.println(str);
    }
}
------解决方案--------------------
        String msg = (String) m.invoke(theBean,