下面是一个小测试代码,它将背景设置为itext块对象。我打算做的是使用反射块块=新块()、BaseColor baseColor =新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();
}
}
}这就是我得到的
sun.reflect.NativeMethodAccessorImpl.invoke0(Native方法中的参数类型不匹配(在sun.reflect.NativeMethodAccessorImpl.invoke(Unknown源)在sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown源)在com.blubench.test.BaseColorReflection.main(BaseColorReflection.java:33)处的java.lang.reflect.Method.invoke(未知源)
这是一个很常见的问题,但我不知道是什么原因造成的?
发布于 2014-02-22 05:46:10
传递参数实例,而不是参数的类:
变化
method.invoke(chunk, baseColorObject.getClass());至
method.invoke(chunk, baseColorObject);https://stackoverflow.com/questions/21950184
复制相似问题