dimanche 14 novembre 2021

How to invoke a java method without knowing parameter types using reflection in java

I'm trying to execute this string in java using reflection

String methodCall = "com.mypackage.util.MathUtil.myFunction(4,\"abc\")";

This code does the job for me (after little string parsing)

Class.forName("com.mypackage.util.MathUtil").getDeclaredMethod("myFunction", int.class, String.class).invoke(null, 4, "abc");

The problem with the above solution is that i need to know the parameter types before invoking the method, and unfortunately i don't have them.

As a solution i can get all declared methods using Class.forName("com.mypackage.util.MathUtil").getDeclaredMethods() , iterate, match name and parameter count, and manually check types with some logic to identify the appropriate method.

Can java do this heavy lifting for me with something like this

Class.forName("com.mypackage.util.MathUtil").getDeclaredMethod("myFunction").invoke(null, 4, "abc");

This code should try to match the appropriate method and can throw NoSuchMethodException or Ambiguity error when 2 or more similar methods matched. Also feel free to suggest other ways to achieve this use case.





Aucun commentaire:

Enregistrer un commentaire