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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With