Hi i am using reflections to achieve something. I have been given class name, method name of that class and parameter values that needs to be passed to that method in a file(Take any file. Not a constraint). I have to call that method with the parameters. This methods do not return anything. There is a huge list of methods in this classes and parameter list of each varies.
E.g: method1(String, String, int, boolean)
method1(String, int, boolean)
and likewise i have different permutations and combinations.
So how can i achieve this.
I have tried hard coding things with different switch clauses but it is a real overhead and risky thing to maintain.
Can we dynamically do this thing, like on the fly read the method name and its parameter from the file and call it.
Any small code snippet will be helpful.
TIA.
Output:
Hope this helps.
I don't know if this is a newer feature in Java, but I have seen that you can use invoke now with parameters as well, instead of using an array, which might make your code better to read (This is the alternative way). If you need a variable number of arguments and you don't know beforehand how many there will be, allocating the array is defeinitly working and should also be backwardcompatible.
A simple solution would be to create a
Class
with the Arguments required to be passed:Assuming that you want to invoke a class
Foo
with a method namedbar
.Then it would be done like this.
Hi all i have found the solution to the above question. below is the sample code snippet.
I hope this will help others too.