缺少 Class.isInstance() 的 GWT 解决方法 [英] GWT work-around for missing Class.isInstance()

查看:20
本文介绍了缺少 Class.isInstance() 的 GWT 解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 GWT 中编写一个作业调度系统,该系统维护一组异常(Class[] exceptions),这可能通过重试作业来解决.为此,如果调度程序捕获到异常,我需要查看此异常是否与数组中的类之一匹配.所以,我想要一个这样的功能:

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;
}

遗憾的是 Class.isInstance(...) 在 GWT 中不可用.

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;
}

不幸的是,这种方法不支持针对接口的测试,我也不知道如何解决这个问题,因为 Class.getInterfaces() 也不可用.但是,在所有其他情况下(不包括接口),这种方法是否至少与 Java 的 Class.isInstance 以相同的方式工作?具体来说,如果我查看 GWT 的 Class.java 源代码getSuperclass() 方法包含对 isClassMetadataEnabled() 的检查,其中可能会返回 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?

推荐答案

我使用以下代码:

 public static <T> boolean isInstanceOf(Class<T> type, Object object) {
    try {
         T objectAsType = (T) object;
     } catch (ClassCastException exception) {
         return false;
     }
     return true;
 }

这篇关于缺少 Class.isInstance() 的 GWT 解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆