【IllegalArgumentException】: object is not an instance of declaring class

java.lang.IllegalArgumentException: object is not an instance of declaring classjava

日前在調試動態代理的例子中,出現以上報錯,關鍵代碼以下:數組

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    System.out.println("執行" + method.getName());


    if (method.getName().equals("writeFile")){

        Method method1 = proxy.getClass().getMethod("fetchData");
        Method method2 = proxy.getClass().getMethod("makeContent", Object.class);
        List<Object> dataList = (List<Object>) method1.invoke(proxy);

        try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("D:/Test/test/123.txt"))){
            for (Object o : dataList) {
                String oneInfo = (String) method2.invoke(obj,o);
                bufferedWriter.write(oneInfo);
            }
        }
        return null;

    }else {
        return method.invoke(obj,args);
    }
}

第15行
String oneInfo = (String) method2.invoke(obj,o);
應改成
String oneInfo = (String) method2.invoke(proxy,o);
爲什麼會這樣?咱們先來了解一下invoke()方法:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {}
官方JDK是這樣解釋的:ide

A method invocation on a proxy instance through one of its proxy interfaces will be dispatched to the invoke method of the instance's invocation handler, passing the proxy instance,a java.lang.reflect.Method object identifying the method that was invoked, and an array of type Object containing the arguments.A method invocation on a proxy instance through one of its proxy interfaces will be dispatched to the invoke method of the instance's invocation handler, passing the proxy instance,a java.lang.reflect.Method object identifying the method that was invoked, and an array of type Object containing the arguments.
經過一個代理接口對代理實例的方法調用將被分派到實例調用處理程序的調用方法,傳遞代理實例、標識被調用方法的java.lang.reflect.Method對象和一個包含參數的object類型數組。fetch

  • Object proxy:代理實例
  • Method method:被調用的方法
  • Object[] args:被調用方法的參數

咱們能夠看到,與22行的區別是代理實例的不一樣,而代理是實例的不一樣是由於調用方法的不一樣,method1方法是經過代理實例proxy得到,因此它必須傳入代理實例proxy,而method方法代理的是該類的一個變量obj,更深刻的瞭解後續探討。spa

相關文章
相關標籤/搜索