我如何判断 Java class 是 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 的实例,模块中的一个 class 会执行一些自定义逻辑。
if (methodArgument instanceof OtherLibraryClass) {
doSomethingWithOtherLibraryClass((OtherLibraryClass) methodArgument);
}
理想情况下,我想让其他库成为可选依赖项,因此只有实际使用该库的模块才需要将其拉入:
dependencies {
compileOnly 'com.example:my-optional-dependency:1.0.0'
}
但是,我不确定如何针对甚至可能不在 class 路径上的 class 进行 instanceof
检查。有没有办法在不需要 class 路径上的 class 的情况下进行此实例检查?我有以下手动方法(使用 ClassUtils.hierarchy
from Apache Commons Lang 获取所有 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()));
}
这种方法感觉有点重量级,因为它每次都需要遍历每个超类型。这感觉像是应用程序已经在使用的 Spring 或 Spring 引导框架可能已经提供的东西。
是否有更直接的 and/or 性能方法来确定给定对象是否是可能不在 class 路径上的特定 class 的实例?
一种方法是反射加载 Class
对象并将其用于实例检查,如果 class 不在 class 路径上则返回 false:
private static boolean isInstance(Object instance, String className) {
try {
return Class.forName(className).isInstance(instance);
} catch (ClassNotFoundException e) {
return false;
}
}
如果需要,class 可以根据其名称进行缓存以供将来调用,以避免每次检查时反射 class creation/lookup 的开销。
我正在使用一个多模块 Gradle Spring 引导应用程序,它有一个共享的“库”模块,该模块具有在其他模块之间共享的通用功能。如果传入的值是来自另一个库的给定 class 的实例,模块中的一个 class 会执行一些自定义逻辑。
if (methodArgument instanceof OtherLibraryClass) {
doSomethingWithOtherLibraryClass((OtherLibraryClass) methodArgument);
}
理想情况下,我想让其他库成为可选依赖项,因此只有实际使用该库的模块才需要将其拉入:
dependencies {
compileOnly 'com.example:my-optional-dependency:1.0.0'
}
但是,我不确定如何针对甚至可能不在 class 路径上的 class 进行 instanceof
检查。有没有办法在不需要 class 路径上的 class 的情况下进行此实例检查?我有以下手动方法(使用 ClassUtils.hierarchy
from Apache Commons Lang 获取所有 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()));
}
这种方法感觉有点重量级,因为它每次都需要遍历每个超类型。这感觉像是应用程序已经在使用的 Spring 或 Spring 引导框架可能已经提供的东西。
是否有更直接的 and/or 性能方法来确定给定对象是否是可能不在 class 路径上的特定 class 的实例?
一种方法是反射加载 Class
对象并将其用于实例检查,如果 class 不在 class 路径上则返回 false:
private static boolean isInstance(Object instance, String className) {
try {
return Class.forName(className).isInstance(instance);
} catch (ClassNotFoundException e) {
return false;
}
}
如果需要,class 可以根据其名称进行缓存以供将来调用,以避免每次检查时反射 class creation/lookup 的开销。