从外部检查 Java 对象层次结构 [英] Check Java Object Hierarchy Externally
本文介绍了从外部检查 Java 对象层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有字符串Bar",我想知道 Bar 是否是有效对象,以及Bar"是否扩展了Foo".我会使用 Java 反射还是有更好的方法,比如数据库?我该怎么做?
Say I have the string "Bar" and I want to know whether or not Bar is a valid object, and further, whether "Bar" extends "Foo". Would I be using Java reflection or is there a better way, like a database? and how would I do it?
干杯
推荐答案
如果你不知道包——只知道类名,你可以试试这个,使用 spring 框架:
In case you don't know the package - only the class name, you could try this, using spring framework:
List<Class> classes = new LinkedList<Class>();
PathMatchingResourcePatternResolver scanner = new
PathMatchingResourcePatternResolver();
// this should match the package and the class name. for example "*.Bar"
Resource[] resources = scanner.getResources(matchPattern);
for (Resource resource : resources) {
Class<?> clazz = getClassFromFileSystemResource(resource);
classes.add(clazz);
}
public static Class getClassFromFileSystemResource(Resource resource) throws Exception {
String resourceUri = resource.getURI().toString();
// finding the fully qualified name of the class
String classpathToResource = resourceUri.substring(resourceUri
.indexOf("com"), resourceUri.indexOf(".class"));
classpathToResource = classpathToResource.replace("/", ".");
return Class.forName(classpathToResource);
}
上述两个方法为您提供了名为Bar"的类列表(它们可能不止一个!).
The two above methods give you the list of classes that are named "Bar" (they may be more than one!).
那就更简单了
expectedSuperclass.isAssignableFrom(yourClass);
这篇关于从外部检查 Java 对象层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文