spring—如何判断java类是否是类路径上可能不存在的类或接口的示例?

utugiqy6  于 2021-07-15  发布在  Java
关注(0)|答案(1)|浏览(332)

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

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

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

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

但是,我不知道该怎么做 instanceof 检查甚至可能不在类路径上的类。有没有一种方法可以在不需要类路径上的类的情况下进行示例检查?我有以下手动方法(使用 ClassUtils.hierarchy 从apache commons lang获取所有超类和超级接口:

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引导框架提供的东西。
有没有更直接和/或更有效的方法来确定给定对象是否是某个特定类的示例,而该类可能不在类路径上?

voj3qocg

voj3qocg1#

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

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

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

相关问题