0

I have java classes with different kind of methods. No parameter is needed to invoke some methods. Some methods takes 1 string parameter and some takes 1 string, 1 int params and etc. My point is there are different kind of methods as I told at the beginning. I put a dummy class above to make it easier to understand.

Is it possible to call random method if I have package/class/method name and parameters with reflection?

 package dummyPackage; public class DummyClass { public DummyClass() { super(); // TODO Auto-generated constructor stub } public void foo() { System.out.println("foo called"); } public void bar(int sth) { System.out.println(sth++); } public void doSth(int a,String b) { System.out.println(a + "|" + b); } ... } 

And below is showing what I need. I'm so new to java and have no idea how to solve this.

Object noparams[] = {}; Object[] params1 = new Object[1]; params1[0] = 100; Object[] params2 = new Object[2]; params2[0] = 200; params2[1] = "Test"; //What I need NeededClass.reflect("dummyPackage.dummyClass.foo",noparams); NeededClass.reflect("dummyPackage.dummyClass.bar",params1); NeededClass.reflect("dummyPackage.dummyClass.doSth",params2); 
0

2 Answers 2

2

this should work

 Object[][] params = {{}, {1}, {1, "xxx"}}; Method[] methods = {DummyClass.class.getMethod("foo"), DummyClass.class.getMethod("bar", int.class), DummyClass.class.getMethod("doSth", int.class, String.class)}; for(int i = 0; i < 100; i++) { int m = new Random().nextInt(3); methods[m].invoke(new DummyClass(), params[m]); } 
Sign up to request clarification or add additional context in comments.

3 Comments

But, what if I don't know order of called methods? As I mentioned there are many methods with many classes. In this case you aren't calling methods "randomly". Thanks anyway.
Well, I create methods and args manually, thats true. But methods are called randomly, m is a random index between 0 and 2
Oh hold on. Sorry for my first answer. I just realized you are doing what I exactly need! Thanks!
1

You can get the list of methods of the class using:

Method[] methods = DummyClass.class.getDeclaredMethods(); 

Then just use the Random class to get the index of the method that you want to call (randomly) and get it from the array

int i = Random.nextInt(methods.length); Method method = methods[i]; 

Then get the list of parameters of the method and use it to call it

Class<?>[] params = method.getParameterTypes(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.