Reputation: 309
I currently have this code:
public class Pants {
public static void main(String[] args) {
Pants pants = new Pants();
pants.eat(10, 10.3, "Nice.");
Object[] params = {(long)10, 10.3, "Nice."};
Method eatMethod = pants.getClass().getMethods()[0];
try
{
eatMethod.invoke(pants, params);
} catch (IllegalAccessException | InvocationTargetException e)
{
e.printStackTrace();
}
}
public void eat(long amount, double size, String name) {
System.out.println("You ate");
}
}
It always throws
IllegalArgumentException: wrong number of arguments.
This happened with other methods too. I used the same parameters in eat()
as in method.invoke
, and the types are the same. The error is thrown on
eatMethod.invoke(pants, params);
Upvotes: 1
Views: 2143
Reputation: 309
It turns out that when I used getMethods()[0]
, I was getting the main method and calling that, which obviously has no parameters so it didn't work. Ideally I should've used
getMethod("eat", long.class, double.class, String.class)
which does work.
Upvotes: 1
Reputation: 2608
As the comments say. We don't know wich method is pants.getClass().getMethods()[0]
. Try to get the name with eatMethod.getName()
and see if is really the method eat. If
not you can try with this.
java.lang.reflect.Method method;
method = pants.getClass().getMethod("eat", Long.class, Double.class, String.class);
.
.
.
method.invoke(pants,params );
Also... Checking the Java Docs The methods are never sorted
The elements in the returned array are not sorted and are not in any particular order.
So sometimes your code might work and sometimes not.
Upvotes: 3