繁体   English   中英

如何判断 Java class 是否是 class 的实例或可能不在类路径上的接口?

[英]How can I tell whether a Java class is an instance of a class or interface that might not be on the classpath?

我正在使用一个多模块 Gradle Spring 引导应用程序,该应用程序具有一个共享的“库”模块,该模块具有在其他模块之间共享的通用功能。 如果传入的值是来自另一个库的给定 class 的实例,则模块中的一个类正在执行一些自定义逻辑。

if (methodArgument instanceof OtherLibraryClass) {
  doSomethingWithOtherLibraryClass((OtherLibraryClass) methodArgument);
}

理想情况下,我想让其他库成为可选依赖项,因此只有实际使用该库的模块需要将其拉入:

dependencies {
  compileOnly 'com.example:my-optional-dependency:1.0.0'
}

但是,我不确定如何对可能不在类路径上的 class 进行instanceof检查。 有没有办法在不需要类路径上的 class 的情况下进行此实例检查? 我有以下手动方法(使用ClassUtils.hierarchy Commons Lang中的 ClassUtils.hierarchy 来获取所有超类和超接口:

    if (isInstance(methodArgument, "com.example.OtherLibraryClass")) {
      doSomethingWithOtherLibraryClass((OtherLibraryClass) methodArgument);
    }
  }

  private static boolean isInstance(Object instance, String className) {
    if (instance == null) {
      return false;
    }
    return StreamSupport.stream(
            ClassUtils.hierarchy(obj.getClass(), ClassUtils.Interfaces.INCLUDE).spliterator(),
            false
    ).anyMatch(c -> className.equals(c.getName()));
  }

这种方法感觉有点重,因为它每次都需要迭代每个超类型。 这感觉像是可能已经提供的东西,例如应用程序已经在使用的 Spring 或 Spring 引导框架。

是否有更直接和/或高性能的方法来确定给定的 object 是否是可能不在类路径上的特定 class 的实例?

一种方法是反射加载Class object 并将其用于实例检查,如果 class 不在类路径上,则返回 false:

private static boolean isInstance(Object instance, String className) {
    try {
        return Class.forName(className).isInstance(instance);
    } catch (ClassNotFoundException e) {
        return false;
    }
}

如果需要,可以根据其名称缓存 class 以供将来调用,以避免每次检查时反射 class 创建/查找的开销。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM