0

I'm trying this code http://ideone.com/gymUrP

Object obj2 = coll.getClass().getMethod("find").invoke(coll, new Object[]{});

is working with an empty second argument (matching find() method) but I didn't manage to make the other methods work, like the one with this signature (Docs)

The exception returned is always java.lang.IllegalArgumentException: wrong number of arguments

edit

Thanks to answers, this is close to what I'll need: (a bit heavy though)

Object[] args = new Object[]{new BasicDBObject("a", 2)};
Class[] types = new Class[args.length];
for (int i=0; i<args.length; i++)
    types[i] = (Class) args[i].getClass().getGenericInterfaces()[0];

Object obj = coll.getClass().getMethod("find", types).invoke(coll, args);
System.out.println(obj);
Community
  • 1
  • 1

2 Answers2

2

It should work with this call, passing a DBOject parameter and getting the method expecting this parameter:

DBOject dbo = ...
Object obj2 = coll.getClass().getMethod("find", DBOject.class).invoke(coll, dbo);

(I assume coll is a DBCollection object.)

Guillaume
  • 5,535
  • 1
  • 24
  • 30
  • This would be another method, however, basically it should work as well. But I think it should be `new Class[]{ DBOject.class };` instead of `DBOject.class`. – Trinimon Dec 27 '13 at 17:26
  • Object obj2 = coll.getClass().getMethod("find", DBObject.class).invoke(coll, new Object[]{new BasicDBObject("a", 2)}); works but this isn't easy to use, (it was meant to be really dynamic and use other possible signatures easily) –  Dec 27 '13 at 17:26
  • 1
    `Class.getMethod` takes a `Class>...` vararg, no need to explcitly create the array. I also simplified the `invoke` call. – Guillaume Dec 27 '13 at 17:32
  • ctrl, the Reflection API does not allow such a dynamic call. At best you can guess the arguments in your code or iterate over all class methods and invoke the first whose arguments match your needs. – Guillaume Dec 27 '13 at 17:34
0

Looking at the Reflection API I'd say you missed the parameterTypes. I'd assume it to be:

Object obj2 = coll.getClass().getMethod("find", new Class[]{})
                             .invoke(coll, new Object[]{});

or

Object obj2 = coll.getClass().getMethod("find",null)
                             .invoke(coll, new Object[]{});

Look at this example as well.

Trinimon
  • 13,839
  • 9
  • 44
  • 60