I'm trying to write a job scheduling system in GWT that maintains an array of exceptions (Class<? extends Exception>[] exceptions
), that might be resolved by retrying the job. For this, if the scheduler catches an exception, I need to see if this exception matches one of the classes in the array. So, I would like to have a function like this:
boolean offerRetry(Exception exception) {
for (Class<? extends Exception> e: exceptions)
if (e.isInstance(exception)) return true;
return false;
}
Unfortunately Class.isInstance(...)
isn't available in GWT.
Is there a good work-around for this? My current best guess is something like this:
public static boolean isInstance(Class<?> clazz, Object o) {
if ((clazz==null) || (o==null)) return false;
if (clazz.isInterface()) throw new UnsupportedOperationException();
Class<?> oClazz = o.getClass();
while (oClazz!=null) {
if (oClazz.equals(clazz)) return true;
oClazz = oClazz.getSuperclass();
}
return false;
}
Unfortunately, this approach does not support testing against interfaces, and I don't have any idea how to fix that either as Class.getInterfaces()
is also not available. But would this approach at least work the same way as Java's Class.isInstance
in all other cases, excluding interfaces? Specifically, if I look at GWT's source for Class.java, the getSuperclass()
method contains a check of isClassMetadataEnabled()
, which might return false (but I don't know in which cases), as it contains a comment saying "This body may be replaced by the compiler".
Or is there a better way entirely to do this?
I use following code:
public static <T> boolean isInstanceOf(Class<T> type, Object object) {
try {
T objectAsType = (T) object;
} catch (ClassCastException exception) {
return false;
}
return true;
}
Maybe something like this would help:
boolean offerRetry(Exception exception) {
try{
throw exception;
} catch (SpecException se) {
return true;
} catch (SpecException1 se1) {
return true;
...
} catch (Exception e) {
return false;
}
}
It depends on how you construct the array of exceptions. If the java 7 stuff works properly then you could put all exceptions in one catch:
boolean offerRetry(Exception exception) {
try{
throw exception;
} catch (SpecException | SpecException1 | ... se) {
return true;
} catch (Exception e) {
return false;
}
}
来源:https://stackoverflow.com/questions/23188913/gwt-work-around-for-missing-class-isinstance