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);

2 Answers2

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]);
    }
Evgeniy Dorofeev
  • 124,221
  • 27
  • 187
  • 258
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();
iberbeu
  • 12,251
  • 5
  • 24
  • 47