使用反射调用具有参数的内部类方法

时间:2018-09-27 06:39:45

标签: java methods reflection

我正在尝试测试我的代码,尽管知道使用反射不是测试的好方法。我有一个公开的外部类,有一个私有的内部类,使用下面的public方法,

>>> print(openpyxl.__version__)
2.5.8
>>> wb1 = openpyxl.load_workbook('test')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\stephinj\AppData\Local\Programs\Python\Python37-32\lib\site-packages\openpyxl\reader\excel.py", line 175, in load_workbook
archive = _validate_archive(filename)
  File "C:\Users\stephinj\AppData\Local\Programs\Python\Python37-32\lib\site-packages\openpyxl\reader\excel.py", line 122, in _validate_archive
archive = ZipFile(filename, 'r', ZIP_DEFLATED)
  File "C:\Users\stephinj\AppData\Local\Programs\Python\Python37-32\lib\zipfile.py", line 1182, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'test'

我的主要Java类如下所示

File "C:\Users\stephinj\AppData\Local\Programs\Python\Python37-32\lib\site-packages\openpyxl\chart\reader.py", line 50, in find_charts
drawing = SpreadsheetDrawing.from_tree(tree)

这是扔

  

线程“ main”中的异常java.lang.NoSuchMethodException:car.Outer $ Inner.test()       在java.lang.Class.getDeclaredMethod(Class.java:2130)       在car.A.main(A.java:36)

如何使用反射调用带参数的内部类方法?

1 个答案:

答案 0 :(得分:1)

您需要在对getDeclaredMethod()的调用中提供参数类。当您调用getDeclaredMethod()时,第一个参数是您要查找的方法的名称,其余的参数是所需方法的参数的类。这就是getDeclaredMethod()区分重载方法名称以获得一个特定方法的方式。由于您未提供任何其他参数,因此getDeclaredMethod()正在寻找一种名为test的方法,该方法不包含任何参数。因为在类Outer$Inner中没有这样的方法,您将获得一个异常。您唯一拥有的test方法采用一个int参数`,因此以下操作应该可以实现:

Method method = c.getClass().getDeclaredMethod("test", int.class);

在这里,int.class是与原始参数类型Class对应的int对象。

相关问题