带有Reflection的IllegalArgumentException

时间:2014-02-22 05:30:42

标签: java reflection itext

这是一个小的测试代码,用于设置itext块对象的背景。我打算做的是使用反射在块对象上执行以下方法 Chunk chunk = new Chunk(); BaseColor baseColor = new BaseColor(45,90,135); chunk.setBackground(baseColor);

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.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(未知来源)at   sun.reflect.DelegatingMethodAccessorImpl.invoke(未知来源)at   java.lang.reflect.Method.invoke(未知来源)at   com.blubench.test.BaseColorReflection.main(BaseColorReflection.java:33)

这是一个非常常见的问题,但我无法确定导致此问题的原因?

1 个答案:

答案 0 :(得分:0)

传递参数实例,而不是参数的类:

更改

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

method.invoke(chunk, baseColorObject);