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

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

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

  1. if (methodArgument instanceof OtherLibraryClass) {
  2. doSomethingWithOtherLibraryClass((OtherLibraryClass) methodArgument);
  3. }

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

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

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

  1. if (isInstance(methodArgument, "com.example.OtherLibraryClass")) {
  2. doSomethingWithOtherLibraryClass((OtherLibraryClass) methodArgument);
  3. }
  4. }
  5. private static boolean isInstance(Object instance, String className) {
  6. if (instance == null) {
  7. return false;
  8. }
  9. return StreamSupport.stream(
  10. ClassUtils.hierarchy(obj.getClass(), ClassUtils.Interfaces.INCLUDE).spliterator(),
  11. false
  12. ).anyMatch(c -> className.equals(c.getName()));
  13. }

这种方法感觉有点重,因为每次都需要迭代每个超类型。这感觉像是应用程序已经在使用的spring或spring引导框架提供的东西。
有没有更直接和/或更有效的方法来确定给定对象是否是某个特定类的示例,而该类可能不在类路径上?

voj3qocg

voj3qocg1#

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

  1. private static boolean isInstance(Object instance, String className) {
  2. try {
  3. return Class.forName(className).isInstance(instance);
  4. } catch (ClassNotFoundException e) {
  5. return false;
  6. }
  7. }

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

相关问题