by
0
6
3,142
1
Top 1% !
Popular
Famous
Tagged
Specified
OpenSource
Popularity: 4522nd place
Created
Modified Oct 25, 2013

Published on:

JVMjre5
LanguageJava
LicenseMIT_X11

Create a usage pattern for several heterogeneous methods

Let's say we have several methods implemented in the same way but that should invoke different operations inside their implementation.
e.g. we have a wrapper of API, and each API should be checked for the reload of endpoint if failed...
Under these circumstances, C# lambda expressions should be very useful, but what about Java? Here there is a solution.
The best part of this solution is that reflection is not needed and strong typing is preserved.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/11811/Create-a-usage-pattern-for-several-heter?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
public interface CallableOp<T> { T exec(); } /** * This is the generic method that provides the common implementation for several methods, * which are implemented in exec() method of the given input * @param op object of anonymous class that implement the internal logic of the method * @param clazz class of the returning object */ public <T> T execOp(CallableOp<T> op, Class<T> clazz) { try{ return op.exec(); }catch(WebServiceException webSerExc){ if (checkReloadEndpoint(webSerExc)) { //with this exception we prepare reload endpoints and try again invoking ws forcedReloaded = true; return op.exec(); }else{ //forward the exception throw webSerExc; } } } public void test() { //here you don't need any cast nor reflection! boolean res = execOp(new CallableOp<Boolean>() { public Boolean exec() { //parameters and other business logic may be implemented here //or directly in the test() method int param1 = 1; String param2 = "test"; return apiInvocation(param1, param2); // thi is the API invocation method } }, Boolean.class); }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus