Java Reflection: How to pass a method to another so that it can be executed (no interfaces)
I would like to have a method which can invoke a method that is passed to it. The idea is to retry if there is a dead lock exception, and instead of adding a try
catch
to every place I want this, I would rather have a utility 开发者_如何学JAVAthat works like retryExecution(Method method)
. Inside the retryExecution
method is all the reusable logic to handle retrying deadlocks. I would like to do this without the use of AOP and also without the use of an interface (since I am telling the retryExcution method what the method to invoke is, instead of depending on what the method name is via the interface).
You use an interface.
You use an interface.
You use an interface.
Or you use an abstract class, which is a variation on that theme.
If you refuse to follow the design of the language for solving this problem and 'use an interface', you read the javadoc for java.lang.reflect
and obtain a Method
object and pass it around. http://java.sun.com/developer/technicalArticles/ALT/Reflection/
The designers of Java considered and rejected callable methods as first class objects (along the lines of, say, C++ or C function values).
For this purpose you have to provide the Method
instance, the Object
on which you want to call the method and the needed parameters.
See the method invoke
on the documentation.
You will of course have to know the name of the method to retry. If you know the method name and have the object, then calling the method is easy.
public Object retry(Object objectWithTheMethod, String methodName) {
try {
Method method = objectWithTheMethod.getClass().getMethod(methodName);
return method.invoke(objectWithTheMethod);
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (NoSuchMethodException e) {
}
}
It gets just a little more complicated if the method requires some parameters. You would then have to specify the parameter classes to getMethod. I.e. if the method requires one String parameter:
Method method = objectWithTheMethod.getClass().getMethod(methodName, String.class);
This is easy with Lambda Expressions.
Upgrade to Java SE 8.
Write some code using Lambda:
int sum = 0; list.forEach(#{ e -> sum += e.size(); });
Log into freenode and join one of #concatenative, #python, #haskell, or others and congratulate them on their forward thinking
Sell your copy of SICP to pay for a victory dinner.
精彩评论