Java: NoSuchMethodException when method clearly exists

前端 未结 4 764
無奈伤痛
無奈伤痛 2020-12-03 04:28

On my current project, I\'ve felt the need to create a sort of simulated callback system in Java using reflection. However, I\'m having issues getting my reflection to actua

相关标签:
4条回答
  • 2020-12-03 04:49

    The Javadoc for getMethod isn't explicit, but it looks like it might throw a NoSuchMethodException for methods that aren't public, and your method is private.

    0 讨论(0)
  • 2020-12-03 04:52

    You need the parameter list to be absolutely correct for the method you want for the call to succeed.

    I've found that tiny steps are important when doing reflection because the compiler doesn't help. Write a small snippet which actually invokes exactly the method you want to in this particular case, and then when that works, generalize it into the framework here. I would focus on the parameters passed.

    0 讨论(0)
  • 2020-12-03 04:56

    Your method is private but getMethod() only returns public method.

    You need to use getDeclaredMethod().

    0 讨论(0)
  • 2020-12-03 05:03

    The versioning issue that can cause NoSuchMethodException isn't a difference between the compiler versions. It's a difference in the version of (in your case) MyClass at compile time versus runtime.

    Since you're using reflection you issue might have nothing to do with versioning, though. Certainly that would not explain different behavior between getMethod and getDeclaredMethods, because you're running them against the same Class instance, hence a version difference isn't really possible.

    Are you sure that the parameters match your actual method?

    0 讨论(0)
提交回复
热议问题