2014-02-22 47 views
0

這是一個小的測試代碼,它將背景設置爲itext塊對象。我打算做的是使用反射在塊對象上執行以下方法 塊大塊=新的塊(); BaseColor baseColor = new BaseColor(45,90,135); chunk.setBackground(baseColor);帶反射的IllegalArgumentException

package com.blubench.test; 

import java.lang.reflect.Constructor; 
import java.lang.reflect.InvocationTargetException; 
import java.lang.reflect.Method; 

import com.itextpdf.text.Chunk; 

public class BaseColorReflection { 

    static final String methodName = "setBackground"; 
    static final String className = "com.itextpdf.text.Chunk"; 
    static final String param = "com.itextpdf.text.BaseColor"; 


    public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { 

     //**********Target Class************** 
     Class<?> chunkClass = Class.forName(className); 
     Chunk chunk = (Chunk) chunkClass.newInstance(); 

     //*********Parameter to Target Method********* 
     Class<?> baseColorClass = Class.forName(param);  
     Class<?>[] argTypes = {int.class,int.class,int.class}; 
     Constructor<?> baseColorCtor = baseColorClass.getDeclaredConstructor(argTypes);  
     Object[] argValues = {45,90,135}; 
     Object baseColorObject = baseColorCtor.newInstance(argValues); 

     //*********Target Method**************** 
     Method method = chunkClass.getDeclaredMethod(methodName,baseColorObject.getClass()); 

     try { 

      //***********Invoke Target Method on Target Class with Parameter********** 
      method.invoke(chunk, baseColorObject.getClass()); 

     } catch (IllegalArgumentException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IllegalAccessException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (InvocationTargetException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

} 

這就是我得到

java.lang.IllegalArgumentException異常:在 sun.reflect.NativeMethodAccessorImpl.invoke在 sun.reflect.NativeMethodAccessorImpl.invoke0(本機方法)的參數類型不匹配(來源不明)處 java.lang.reflect.Method.invoke(來源不明) sun.reflect.DelegatingMethodAccessorImpl.invoke(來源不明)在 com.blubench.test.BaseColorReflection.main(BaseColorReflection.java:33)

這是一個非常普遍的問題,但我無法確定是什麼原因造成的?

回答

0

傳遞參數的實例,而不是類的參數:

變化

method.invoke(chunk, baseColorObject.getClass()); 

method.invoke(chunk, baseColorObject);