【问题标题】:IllegalArgumentException with Reflection带有反射的 IllegalArgumentException
【发布时间】:2014-02-22 05:30:42
【问题描述】:

这是一个小测试代码,用于将背景设置为 itext 块对象。我打算做的是使用反射在块对象上执行以下方法 块块 = 新块(); 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) 在 sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(未知来源)在 java.lang.reflect.Method.invoke(未知来源)在 com.blubench.test.BaseColorReflection.main(BaseColorReflection.java:33)

这是一个非常常见的问题,但我无法确定是什么原因造成的?

【问题讨论】:

    标签: java reflection itext


    【解决方案1】:

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

    改变

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

    method.invoke(chunk, baseColorObject);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-09
      • 2011-08-25
      • 1970-01-01
      • 2013-01-18
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多