Reputation: 7179
In my programm I tried to call a method over reflection with this code:
private void invokeMethod(Component sender, MouseEvent event)
{
try
{
System.out.println(name);
Method method = frame.getClass().getMethod("onButton1Clicked", Component.class, MouseEvent.class);
method.invoke(sender, event);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void onButton1Clicked(Component sender, MouseEvent e)
{
System.out.println("Test");
}
But if I run this code it comes to this exception:
java.lang.IllegalArgumentException: object is not an instance of declaring class
Any ideas where my mistake is?
Upvotes: 0
Views: 51
Reputation: 22692
If the method in question is part of the Frame class, you need to invoke it on an instance of Frame.
A quick look at the JavaDoc tells you the first argument should be the instance on which the method will be invoked.
Try this:
method.invoke(frame, sender, event);
Upvotes: 1