JaCoCo and missed coverage of private default constructor - java

I'd like to see an example to prevent JaCoCo to report private empty constructors as non-covered code in a Java class.
In the maven plugin configuration I have
<rule>
<element>CLASS</element>
<excludes>
<exclude>JAVAC.SYNTHCLASS</exclude>
<exclude>JAVAC.SYNTHMETH</exclude>
</excludes>
</element>
</rule>
Isn't there something similar for the constructor?

This is not supported. The official documentation says:
Filters for Code where Test Execution is Questionable or Impossible by Design
Private, empty default constructors - assuming no calls to it
Plain getters and setters
Blocks that throw AssertionErrors - Entire block should be ignored if a condition (if !assertion throw new AssertionError)
see also : https://github.com/jacoco/jacoco/issues/298
Update: This was fixed in https://github.com/jacoco/jacoco/pull/529 and should be in 0.8.0.

There is no way to turn that option off. If you desperately need to meet some quality gate related to coverage you can always use a workaround and invoke these private constructors via reflection.

For this use case, reflection is perfectly acceptable, there are few and well known classes. The bellow code could be used with an automatic class detection based on the name. For sample ".*Factory" classes with additional asserts.
#Test
public void testCoverage()
throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
coverageSingleton(MySingleton1.class);
coverageSingleton(MySingleton2.class);
}
private <S> void coverageSingleton(Class<S> singletonClass)
throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
final Constructor<S> constructor = singletonClass.getDeclaredConstructor();
constructor.setAccessible(true);
constructor.newInstance();
}

As per official documentation, it's going to be released with 0.8.0
Filters for Code where Test Execution is Questionable or Impossible by
Design
Private empty constructors that do not have arguments - Done
You can find details here.

This is not solving the essential problem that empty private constructors should not need coverage, but to actually make JaCoCo report coverage on an empty private constructor you need to call it. How do you do that? You call it in the static initialization block.
public class MyClass {
static {
new MyClass();
}
private MyClass(){}
}
EDIT:
Turned out that there is no guarantee on the static initialization block to be executed. Thus we are limited to using methods as this one:
static <T> void callPrivateConstructorIfPresent(Class<T> clazz){
try{
Constructor<T> noArgsConstructor = clazz.getDeclaredConstructor();
if(!noArgsConstructor.isAccessible()){
noArgsConstructor.setAccessible(true);
try {
noArgsConstructor.newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
{
e.printStackTrace();
}
noArgsConstructor.setAccessible(false);
}
} catch(NoSuchMethodException e){}
}

As 0.8.0 is not yet released, I created a hamcrest matcher that checks whether a class is an utility class and additionally calls the private constructor using reflection (for code coverage purpose only).
https://github.com/piotrpolak/android-http-server/blob/master/http/src/test/java/ro/polak/http/utilities/IOUtilitiesTest.java
package ro.polak.http.utilities;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static ro.polak.http.ExtraMarchers.utilityClass;
public class IOUtilitiesTest {
#Test
public void shouldNotBeInstantiable() {
assertThat(IOUtilities.class, is(utilityClass()));
}
}
https://github.com/piotrpolak/android-http-server/blob/master/http/src/test/java/ro/polak/http/ExtraMarchers.java
package ro.polak.http;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ExtraMarchers {
private static final UtilClassMatcher utilClassMatcher = new UtilClassMatcher();
public static Matcher<? super Class<?>> utilityClass() {
return utilClassMatcher;
}
private static class UtilClassMatcher extends TypeSafeMatcher<Class<?>> {
#Override
protected boolean matchesSafely(Class<?> clazz) {
boolean isUtilityClass = false;
try {
isUtilityClass = isUtilityClass(clazz);
} catch (ClassNotFoundException | InstantiationException e) {
// Swallowed
}
// This code will attempt to call empty constructor to generate code coverage
if (isUtilityClass) {
callPrivateConstructor(clazz);
}
return isUtilityClass;
}
#Override
protected void describeMismatchSafely(Class<?> clazz, Description mismatchDescription) {
if (clazz == null) {
super.describeMismatch(clazz, mismatchDescription);
} else {
mismatchDescription.appendText("The class " + clazz.getCanonicalName() + " is not an utility class.");
boolean isNonUtilityClass = true;
try {
isNonUtilityClass = !isUtilityClass(clazz);
} catch (ClassNotFoundException e) {
mismatchDescription.appendText(" The class is not found. " + e);
} catch (InstantiationException e) {
mismatchDescription.appendText(" The class can not be instantiated. " + e);
}
if (isNonUtilityClass) {
mismatchDescription.appendText(" The class should not be instantiable.");
}
}
}
#Override
public void describeTo(Description description) {
}
private void callPrivateConstructor(Class clazz) {
try {
Constructor<?> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
constructor.newInstance();
} catch (NoSuchMethodException | IllegalAccessException |
InstantiationException | InvocationTargetException e) {
// Swallowed
}
}
private boolean isUtilityClass(Class clazz) throws ClassNotFoundException, InstantiationException {
boolean hasPrivateConstructor = false;
try {
clazz.newInstance();
} catch (IllegalAccessException e) {
hasPrivateConstructor = true;
}
return hasPrivateConstructor;
}
}
}

Related

EasyMock still goes into implementation of a method mocked with addMockedMethod

I am trying to write a unit-test in Java. Due to the structure of Java class, I have to come up with a way in which whenever a constructor of a class is called, a mocked object of that class is created. I want to mock 2 methods of that class.
CallToBeMocked mockCallToBeMocked = EasyMock.createMockBuilder(CallToBeMocked.class)
.withConstructor(ArgumentA.class, ArgumentB.class, ArgumentC.class)
.withArgs(mockArgumentA, mockArgumentB, mockArgumentC)
.addMockedMethod("isProxied", ArgumentA.class)
.addMockedMethod("remoteCall", String.class, ArgumentA.class, Object.class)
.createMock();
EasyMock.expect(mockCallToBeMocked.isProxied(mockArgumentA)).andReturn(false);
EasyMock.expect(mockCallToBeMocked.remoteCall("ip-address", mockArgumentA, null)).andThrow(new Exception()).times(3);
The problem is that although I have clearly specified that isProxied and remoteCall methods have to be mocked and I have given appropriate expectations for those methods, it still starts going into the actual implementations of these methods.
It should perfectly work. So something else is going on. Here is a working example based on your code. What's different from your actual implementation?
public class PartialTest {
public interface ArgumentA { }
public interface ArgumentB { }
public interface ArgumentC { }
public static class CallToBeMocked {
public CallToBeMocked(ArgumentA a, ArgumentB b, ArgumentC c) {
}
public boolean isProxied(ArgumentA a) {
return true;
}
public int remoteCall(String ip, ArgumentA a, Object any) throws Exception {
return 0;
}
}
#Test
public void test() throws Exception {
ArgumentA mockArgumentA = createNiceMock(ArgumentA.class);
ArgumentB mockArgumentB = createNiceMock(ArgumentB.class);
ArgumentC mockArgumentC = createNiceMock(ArgumentC.class);
CallToBeMocked mockCallToBeMocked = createMockBuilder(CallToBeMocked.class)
.withConstructor(ArgumentA.class, ArgumentB.class, ArgumentC.class)
.withArgs(mockArgumentA, mockArgumentB, mockArgumentC)
.addMockedMethod("isProxied", ArgumentA.class)
.addMockedMethod("remoteCall", String.class, ArgumentA.class, Object.class)
.createMock();
expect(mockCallToBeMocked.isProxied(mockArgumentA)).andReturn(false);
expect(mockCallToBeMocked.remoteCall("ip-address", mockArgumentA, null)).andThrow(new Exception()).times(3);
replay(mockCallToBeMocked);
assertFalse(mockCallToBeMocked.isProxied(mockArgumentA));
try {
mockCallToBeMocked.remoteCall("ip-address", mockArgumentA, null);
fail("Should throw");
} catch (Exception e) { }
try {
mockCallToBeMocked.remoteCall("ip-address", mockArgumentA, null);
fail("Should throw");
} catch (Exception e) { }
try {
mockCallToBeMocked.remoteCall("ip-address", mockArgumentA, null);
fail("Should throw");
} catch (Exception e) { }
verify(mockCallToBeMocked);
}
}
If we aren't tied to EasyMock, here's a way in which the same functionality can be achieved using Mockito.
import static org.mockito.Mockito.verify;
import org.mockito.Mockito;
....
ClassToBeMocked myMock = Mockito.mock(ClassToBeMocked.class);
Mockito
.when(myMock.isProxied(any(ArgumentA.class)))
.thenReturn(false);
Mockito
.when(myMock.remoteCall(any(String.class), any(ArgumentA.class), any(Object.class)))
.thenThrow(new Exception("monkeys"));
<USE ``myMock``>
verify(myMock, times(1)).isProxied(mockArgumentA);
verify(myMock, times(3)).remoteCall("ip-address", mockArgumentA, null);

Java accessing static inner class potentially throw NoSuchFieldException

In Java why calling a static nested class won't compile because of a potential NoSuchFieldException and IllegalArgumentEception ?
Here is my classes:
public class DBRef {
public static class CMS_FILE_ROOM extends BuildableDatabaseTable {
public static String _table_name = "cms_file_ROOM";
public static BuildableColumn _ALL = new BuildableColumn._ALL(getCurrentClass());
}
public static SelectQuery SELECT(final BuildableColumn... columnsToSelect) {
return new SelectQuery(columnsToSelect);
}
}
public class SelectQuery extends Query {
public SelectQuery(final BuildableColumn... columnsToSelect) {
super();
for (final BuildableColumn column : columnsToSelect) {
this.columns.add(column.toSQL());
}
}
public Query FROM(final Class<? extends BuildableDatabaseTable> tableClass) throws NoSuchFieldException, IllegalAccessException {
this.froms.add(DatabaseAccesser.toSQL(tableClass));
return this;
}
}
// Method called in both cases just above by some poor designed methods redirection (my bad). But exceptions are catched.
public static String toSQL(final Class<? extends BuildableDatabaseTable> table) {
try {
return (String) table.getField("_table_name").get(null);
} catch (final IllegalAccessException e) {
e.printStackTrace();
} catch (final NoSuchFieldException e) {
e.printStackTrace();
}
return "ERROR";
}
When from anywhere else in my code I do:
SelectQuery lSelectQuery = (SelectQuery) DBRef.SELECT(DBRef.CMS_FILE_ROOM._ALL)
.FROM(DBRef.CMS_FILE_ROOM.class);
I get the following (compile time) error (on the .class call):
I can't find the reason why, I can nest this in a try catch but I'd like to understand why ?

call the same method name from instances different type

I have some libraries from external company, I want to use this API. I try to implement calling this API, my logic should call the same method name. I have duplicate codes, I want to avoid to do this. I'm beginner and subjects like interfaces, polymorphism are little bit difficult to me.
public void modPeople(Object person)
{
if (person instanceof com.company.persontype1)
{
com.company.persontype1 fireman = (com.company.persontype1) person;
String name = fireman.getName();
if (name!=null ) {
...
fireman.set_name();
fireman.save();
}
permissions = fireman.get_Permissions();
...
permissions = fixperm (permissions);
fireman.set_Permissions();
};
if (person instanceof com.company.persontype2)
{
com.company.persontype2 nurse = (com.company.persontype2) person;
String name = nurse.getName();
if (name!=null ) {
...
nurse.set_name();
nurse.save();
}
permissions = nurse.get_Permissions();
...
permissions = fixperm (permissions);
nurse.set_Permissions();
};
}
First of all I should mention that the methodology which you requested in your question is called "Duck Typing". Generally this technology is possible in Java (see below the example) but it's not widely used in Java. There could be performance hits etc. It would be much better to introduce a proper inheritance/interface level instead.
Also the provided example don't deal with exceptions properly etc. It's just a quick and quite dirty "demostration of the technology". Feel free to adapt it for your needs.
It's Java7 (for multi-catch clauses, you may refactor this with ease).
ISomeIterface.java (it contains all common methods implemented by classes which are used in your "bad code"):
package org.test;
public interface ISomeInterface {
public String getName();
public void setName(String _name);
public void save();
// specify other common methods
}
ReflectCaller.java:
package org.test1;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import org.test.ISomeInterface;
public class ReflectCaller {
private final Method[] methods = ISomeInterface.class.getDeclaredMethods();
private final Map<Class<?>, Method[]> maps = new HashMap<Class<?>, Method[]>();
public void inspectClass(Class<?> _clazz) throws NoSuchMethodException, SecurityException {
final Method[] ms = new Method[methods.length];
int i = 0;
for(final Method m: methods) {
ms[i] = _clazz.getMethod(m.getName(), m.getParameterTypes());
i++;
}
maps.put(_clazz, ms);
}
public ISomeInterface wrapper(Object _obj) {
final Method[] ms = maps.get(_obj.getClass());
// To be replaced by guava's Preconditions.checkState()
if (ms == null)
throw new NoSuchElementException(String.format("Class %s is unregistered", _obj.getClass().getName()));
return new SomeInterfaceImpl(_obj, ms);
}
private static class SomeInterfaceImpl implements ISomeInterface {
private final Object obj;
private final Method[] ms;
public SomeInterfaceImpl(Object _obj, Method[] _ms) {
ms = _ms;
obj = _obj;
}
#Override
public String getName() {
try {
return (String) ms[0].invoke(obj);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
#Override
public void setName(String _name) {
try {
ms[1].invoke(obj, _name);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
#Override
public void save() {
try {
ms[2].invoke(obj);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
}
And test class ReflectTest.java. Notice that classes ReflectTest.Test and ReflectTest.Test2 has the same methods as ISomeInterface but don't implement it, they are completely independent from that interface and from each other.
package org.test2;
import org.test.ISomeInterface;
import org.test1.ReflectCaller;
public class ReflectTest {
private final ReflectCaller rc;
ReflectTest(Class ... _classes) throws NoSuchMethodException, SecurityException {
rc = new ReflectCaller();
for(final Class c: _classes)
rc.inspectClass(c);
}
void callSequence(Object _o) {
// this function demonstrates the sequence of method calls for an object which has "compliant" methods
ISomeInterface tw = rc.wrapper(_o);
tw.setName("boo");
System.out.printf("getName() = %s\n", tw.getName());
tw.save();
}
public static class Test {
public String getName() {
System.out.printf("%s.getName()\n", getClass().getName());
return "boo";
}
public void setName(String _name) {
System.out.printf("%s.setName(%s)\n", getClass().getName(), _name);
}
public void save() {
System.out.printf("%s.save()\n", getClass().getName());
}
}
public static class Test2 {
public String getName() {
System.out.printf("%s.getName()\n", getClass().getName());
return "boo2";
}
public void setName(String _name) {
System.out.printf("%s.setName(%s)\n", getClass().getName(), _name);
}
public void save() {
System.out.printf("%s.save()\n", getClass().getName());
}
}
public static void main(String[] args) {
ReflectTest rt;
try {
rt = new ReflectTest(Test.class, Test2.class);
} catch (NoSuchMethodException | SecurityException e) {
System.out.println(e);
System.exit(2);
return;
}
rt.callSequence(new Test());
rt.callSequence(new Test2());
}
}

Null pointer in my Facade :(

I've written a task manager, and well it;'s a long story... all in Java by the way. So I wrote a Facade which you can see below there is a problem with the HashMap and I suspect that the values which I attempt to add into the HashMap during the construction aren't going so well. The method that is triggering the null pointer exception is the create method. the input parameters to the method have been verified by me and my trusty debugger to be populated.
any help here would be great... I'm sure I forgot to mention something so I'll reply to comments asap as I need to get this thing done now.
package persistence;
import java.util.UUID;
import java.util.HashMap;
import persistence.framework.ComplexTaskRDBMapper;
import persistence.framework.IMapper;
import persistence.framework.RepeatingTaskRDBMapper;
import persistence.framework.SingleTaskRDBMapper;
public class PersistanceFacade {
#SuppressWarnings("unchecked")
private static Class SingleTask;
#SuppressWarnings("unchecked")
private static Class RepeatingTask;
#SuppressWarnings("unchecked")
private static Class ComplexTask;
private static PersistanceFacade uniqueInstance = null;
#SuppressWarnings("unchecked")
private HashMap<Class, IMapper> mappers;
public PersistanceFacade() {
mappers = new HashMap<Class, IMapper>();
try {
SingleTask = Class.forName("SingleTask");
RepeatingTask = Class.forName("RepeatingTask");
ComplexTask = Class.forName("ComplexTask");
mappers.put(SingleTask, new SingleTaskRDBMapper());
mappers.put(RepeatingTask, new RepeatingTaskRDBMapper());
mappers.put(ComplexTask, new ComplexTaskRDBMapper());
}
catch (ClassNotFoundException e) {}
}
public static synchronized PersistanceFacade getUniqueInstance() {
if (uniqueInstance == null) {
uniqueInstance = new PersistanceFacade();
return uniqueInstance;
}
else return uniqueInstance;
}
public void create(UUID oid, Object obj) {
IMapper mapper = (IMapper) mappers.get(obj.getClass());
mapper.create(oid, obj);
}
#SuppressWarnings("unchecked")
public Object read(UUID oid, Class type) {
IMapper mapper = (IMapper) mappers.get(type);
return mapper.read(oid);
}
public void update(UUID oid, Object obj) {
IMapper mapper = (IMapper) mappers.get(obj.getClass());
mapper.update(oid, obj);
}
#SuppressWarnings("unchecked")
public void destroy(UUID oid, Class type) {
IMapper mapper = (IMapper) mappers.get(type);
mapper.destroy(oid);
}
}
For Class.forName("RepeatingTask") to return a class you must have a class persistence.RepeatingTask. But in your comment you say that obj.getClass() returns domain.RepeatingTask so it looks to me like you have 2 "RepeatingTask" classes or domain.RepeatingTask is a sub type.
My guess is that your problem lies in the constructor:
try {
SingleTask = Class.forName("SingleTask");
RepeatingTask = Class.forName("RepeatingTask");
ComplexTask = Class.forName("ComplexTask");
mappers.put(SingleTask, new SingleTaskRDBMapper());
mappers.put(RepeatingTask, new RepeatingTaskRDBMapper());
mappers.put(ComplexTask, new ComplexTaskRDBMapper());
}
catch (ClassNotFoundException e) {}
You silently ignore the ClassNotFOundException. If you add logging to the catch I expect it to tell you that the class SingleTask is not found, as I expect that you did not put those classes in the default package.
Given your reply to comments these classes are in the domain. package, so you could try to change to:
try {
SingleTask = Class.forName("domain.SingleTask");
RepeatingTask = Class.forName("domain.RepeatingTask");
ComplexTask = Class.forName("domain.ComplexTask");
mappers.put(SingleTask, new SingleTaskRDBMapper());
mappers.put(RepeatingTask, new RepeatingTaskRDBMapper());
mappers.put(ComplexTask, new ComplexTaskRDBMapper());
}
catch (ClassNotFoundException e) {
log.warn("Cannot load class", e);
}
Btw, adding logging to your code will help to find the reasons behind unexpected behaviour.
Class.forName("SingleTask"); is throwing a ClassCastException, so mappers does not get populated. Since you are ignoring ClassCastExeption in your constructor you have missed that error, it seems.

Java Exception Handling via Strategy Pattern?

I cooked up a class ExceptionHandler<T extends Exception, OptionalReturnType> (see below) to eliminate some (what I view as) boilerplate code which was cluttering up actual implementation, while still providing a hook for explicit Exception handling if desired in the future. For the most part, in my application (essential a scientific computation), there is no such thing as recovery from exceptions - I need a log of the problem so I can fix it, but otherwise I'm just going to re-run once the problem is corrected.
Do other people do this (at least, in my specific application situation)? Is it dumb to do so (if yes, some explanation as to why would be nice)?
ExceptionHandler:
public abstract class ExceptionHandler<ExceptionType extends Exception,OptionalReturn> {
public abstract OptionalReturn handle(ExceptionType e);
//assorted boilerplate ExceptionHandling, e.g.:
public static <ET extends Exception> ExceptionHandler<ET, ?> swallower(final boolean printStackTrace, final String string) {
return new ExceptionHandler<ET,Object>() {
#Override public Object handle(ET e) {
if(printStackTrace) { e.printStackTrace(); }
if(string!=null && !string.isEmpty()) { System.err.println(string); }
return null;
}
};
}
public static <ET extends Exception> ExceptionHandler<ET, ?> swallower() { return swallower(false,null); }
}
example use (which I'm in the process of chopping down so I'm actually not writing quite so much):
public class Getter<From> implements Function<Future<? extends From>, From> {
private ExceptionHandler<InterruptedException,?> IEH;
private ExceptionHandler<ExecutionException,?> EEH;
public static final ExceptionHandler<InterruptedException,?> IEH_SWALLOWER = ExceptionHandler.swallower(true,"Returning null.");
public static final ExceptionHandler<ExecutionException,?> EEH_SWALLOWER = ExceptionHandler.swallower(true,"Returning null.");
private Getter() { this(IEH_SWALLOWER,EEH_SWALLOWER); }
private Getter(ExceptionHandler<InterruptedException,?> IEH, ExceptionHandler<ExecutionException,?> EEH) {
this.IEH = IEH;
this.EEH = EEH;
}
public static <T> Getter<T> make() { return new Getter<T>(); }
public static <T> Getter<T> make(ExceptionHandler<InterruptedException,?> IEH, ExceptionHandler<ExecutionException,?> EEH) {
return new Getter<T>(IEH, EEH);
}
#Override public From apply(Future<? extends From> from) {
if (from==null) throw new NullPointerException("Null argument in call with Getter.");
return getter(from, IEH, EEH);
}
private static <T> T getter(Future<T> src, ExceptionHandler<InterruptedException,?> IEH, ExceptionHandler<ExecutionException,?> EEH) {
try { return src.get(); }
catch (InterruptedException e) { IEH.handle(e); }
catch (ExecutionException e) { EEH.handle(e); }
return null;
}
}
which is used with the Guava libraries to do some embarrassingly-parallel calculations, and makes the actual Iterable transformation of Futures into something like Iterables.transform(futureCollection,Getter.make()) instead of tangle of inner-classes and exception handling.
I find the code honestly hard to follow and understand. It's full of static which is usually a bad sign in OO design and it's hard to follow with the generics.
Wouldn't something simpler like this work as well?
private static <T> T getter(Future<T> src) {
try { return src.get(); }
catch (InterruptedException e) { handle( "some text"); }
catch (ExecutionException e) { handle( e ) }
return null;
}
You can implement as many handle method as necessary in a base class (or in a static utility class) and use them in the catch block as necessary. Methods will be selected based on the signature, so if you want to print the text, you pass the string, if you want the stack trace you pass the exception (or both). Which leads to the combinations:
handle( String msg )
handle( Exception e )
handle( Exception e, String msg )
This solution has less if, which is usually a good sign as well.
But I have maybe missed a point, given that the code you published is just an excerpt of the whole code.
Have a look otherwise at this question, which is also related: Pluggable Error Handling Strategy
EDIT
If the solution I proposed above is too simple for your need, here are two other ways:
public class AbstractGetter<From> implements Function<Future<? extends From>, From> {
private abstract handleInterrupt( Exception e );
private abstract handleExecution( Exception e );
private static <T> T getter(Future<T> src ) {
try { return src.get(); }
catch (InterruptedException e) { handleInterrupt(e) }
catch (ExecutionException e) { handleExecution(e) }
return null;
}
}
And you implement the X concrete class that correspond the various exception handling strategies. That's essentially the template pattern.
You can still use delegation, but at a more coarse-grained level. Instead of providing individual handler, you provide a handler strategy. That's kind of variation of the strategy pattern then.
public interface ErrorStrategy
{
public void handleInterrupt(Exception e);
public void handleExecution(Exception e);
}
public class Getter<From> implements Function<Future<? extends From>, From> {
ErrorStrategy handler = new DefaultErrorStrategy(). // default one
public Getter<From>()
{
}
public Getter<From>( ErrorStrategy h )
{
this.handler = h.
}
private static <T> T getter(Future<T> src ) {
try { return src.get(); }
catch (InterruptedException e) { handler.handleInterrupt(e) }
catch (ExecutionException e) { handler.handleExecution(e) }
return null;
}
}
You can create the X error handling strategies that you need.
I think it's a good solution, but it could benefit from an ExceptionHandlerFactory and some xml files.

Categories