我有一个带有这样签名的私有(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/