2021年3月23日星期二

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

I'm working with a multi-module Gradle Spring Boot application that has a shared "library" module with common functionality shared among the other modules. One of the classes in the module is doing some custom logic if a value passed in is an instance of a given class from another library.

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

Ideally, I'd like to make that other library an optional dependency, so only the modules that actually use that library need to pull it in:

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

However, I'm not sure how to do the instanceof check against a class that might not even be on the classpath. Is there a way to do this instance check without needing the class on the classpath? I've got the following manual approach (using ClassUtils.hierarchy from Apache Commons Lang to get all superclasses & superinterfaces:

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

This approach feels a bit heavyweight, as it needs to iterate over every supertype each time. This feels like something that might already be provided, such as by the Spring or Spring Boot frameworks the application is already using.

Is there a more straightforward and/or performant approach to determining whether a given object is an instance of a particular class that might not be on the classpath?

https://stackoverflow.com/questions/66773780/how-can-i-tell-whether-a-java-class-is-an-instance-of-a-class-or-interface-that March 24, 2021 at 10:06AM

没有评论:

发表评论