java.lang.IllegalArgumentException:使用Reflection时参数类型不匹配

ars*_*nal 5 java reflection

下面是我的代码,我使用反射来调用方法,但我总是得到异常

List<PdAttrKey> attrKeys = new ArrayList<PdAttrKey>();
Properties adapterProps = new Properties();

PdReadRequest pdReadRequest = new PdReadRequest(1L, 1L, (short) 0, new Date(),
dataDurationSec, 2L, 3L, attrKeys, null, adapterProps);

PdAdapterUserReadOnlyGemsReader adapter1 = new PdAdapterUserReadOnlyGemsReader();

PdReader reader = adapter1.acquireReader(pdReadRequest);

UserCacheDoImpl userDos = Some Value;

Method method = getClassMethod("createPdRecordFromUserDO");

// This line is throwing me exception. And I don't know why?
PdRecord onePdsxRecord = (PdRecord) method.invoke(reader, userDos);
Run Code Online (Sandbox Code Playgroud)

这是下面的方法,我从中获取类的所有方法名称.

    private Method getClassMethod(String methodName) {
        Method method = null;

        Method[] methodList = PdAdapterUserReadOnlyGemsReader.PdUserReadOnlyGemsReader.class
                .getDeclaredMethods();
        for (Method m : methodList) {
            if (m.getName().equals(methodName)) {
                method = m;
                method.setAccessible(true);
                break;
            }
        }

        return method;
    }
Run Code Online (Sandbox Code Playgroud)

更多代码: -

private PdRecord createPdRecordFromUserDO(UserCacheDoImpl userCache) {
   // Some code here
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的例外.知道为什么吗?

java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:599)
Run Code Online (Sandbox Code Playgroud)

任何建议都会有很大帮助.

Ale*_*ien 7

请检查是否存在多个名为"createPdRecordFromUserDO"的方法.看起来有不止一个,但有不同的论点.

你的方法getClassMethod返回它找到的第一个方法,但那可能是错误的方法.检查methodList.length是否> 1,然后这是bug的原因.

如果找到具有给定名称的多个方法,请重新考虑您想要做什么.