调用私有(private)方法时出现 Java InvokingTargetException

标签 java reflection

我有一个带有这样签名的私有(private)方法:

private void compressFilesForSend(List<File> files, File archiveFile)

我想通过反射在测试中调用它

Class[] parameterTypes = new Class[2];
        parameterTypes[0] = java.util.List.class;
        parameterTypes[1] = java.io.File.class;

        Method method = SendDB.class.getDeclaredMethod("compressFilesForSend",parameterTypes);
        method.setAccessible(true);
        method.invoke(files, archiveFile);

堆栈跟踪:

java.lang.NoSuchMethodException: com.m1_mm.tools.SendDB.compressFilesForSend(java.util.ArrayList, java.io.File)
    at java.lang.Class.getDeclaredMethod(Class.java:2130)
    at com.m1_mm.tools.SendDBTest.compressFilesForSendTest1(SendDBTest.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)

如何调用这个方法?

最佳答案

您的 Method.invoke 签名错误。您需要传递要调用方法的实例,然后传递参数。

您所做的就是告诉它调用 files 上的方法,并将 archiveFile 作为参数传递;换句话说,你正在做

files.compressFilesForSend(archiveFile);

但将files视为SendDB的实例。

您需要确定要在哪个 SendDB 实例上调用该方法,并将其作为第一个参数传递:

method.invoke(mySendDbInstance, files, archiveFile);

关于调用私有(private)方法时出现 Java InvokingTargetException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33209124/

相关文章:

java - 如何将复杂对象从 Controller 传递到 View (jsp)

java - JPQL IS NOT NULL 返回带有 NULL 的对象

java - 从类名中获取 Gson TypeToken 作为字符串

scala - 我们应该直接使用 ScalaSignature 吗?

java - 使用java从url下载文件时出现异常

java - Spring MVC 中未显示绑定(bind)数据

java - 以编程方式更改 TableLayout 中整个列的背景颜色

java - 运行 JUnit @Test 方法的子集

Java 反射 : Get concrete type of implemented generic interface

Java Hibernate javax.persistence.Transient 关于反射的注解