Reputation: 11
How can I use invoke in method compare(T o1, T o2)
if me
Upvotes: 0
Views: 444
Reputation: 20726
As Aubin pointed out: comparators are called very-very many times! Using a slow reflection in a comparator seems to be a suicide in a magnificent and glorious way. I can't imagine ever having to do that (just because the fact you can't shouldn't compare apples to oranges, and if you only have apples, you already know how to compare them)!
I don't see, why you want to do this. If you'd post the code you have so far, this would be a lot more clear, and we could help you a lot better!
However, to answer your question on how to catch exceptions thrown by a method invoked through reflection:
Look at the API doc for Method.invoke()
It clearly states to throw an InvocationTargetException
when the invoked method terminated by throwing an exception:
InvocationTargetException - if the underlying method throws an exception.
so this is what you could do, using the Throwable.getCause()
to get the original exception:
try {
myMethod.invoke(myArgs...);
} catch(InvocationTargetException e) {
Throwable myOriginalException = e.getCause();
}
Upvotes: 2