Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT work-around for missing Class.isInstance()

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?

like image 693
Markus A. Avatar asked Apr 20 '14 23:04

Markus A.


1 Answers

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;
 }
like image 194
Sergey Bondarev Avatar answered Sep 22 '22 06:09

Sergey Bondarev