本文介绍了GWT解决缺少Class.isInstance()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我试图在GWT中编写一个作业调度系统,该系统维护一个异常数组( Class< ;? extends Exception> []异常),通过重试该作业。为此,如果调度器捕获异常,我需要看看这个异常是否匹配数组中的一个类。所以,我想有一个这样的功能: boolean offerRetry(异常异常){ for ;?extends Exception> e:exceptions) if(e.isInstance(exception))return true; return false;不幸的是 Class.isInstance(...) / code>在GWT中不可用。 有没有一个很好的解决方法?我当前最好的猜测是这样的: 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; } $ b $ p 不幸的是,这种方法不支持接口测试,有任何想法如何解决,因为 Class.getInterfaces()也不可用。但是这种方法在所有其他情况下,除了接口之外,至少工作方式与Java的 Class.isInstance 相同?具体来说,如果我看一下 GWT的Class.java源, getSuperclass()方法包含 isClassMetadataEnabled(),它可能返回false(但我不知道在哪些情况下),因为它包含一个注释这个主体可以被编译器替换。 $ b 解决方案我使用下面的代码: $ b public static< T> boolean isInstanceOf(Class< T> type,Object object){ try { T objectAsType =(T)object; } catch(ClassCastException exception){ return false; } return true; } 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; } 这篇关于GWT解决缺少Class.isInstance()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-29 03:08