假设我有字符串“Bar”,我想知道Bar是否是有效对象,而且“Bar”是否扩展为“Foo”。我会使用Java反射还是有更好的方法,比如数据库?我该怎么做?
干杯
答案 0 :(得分:1)
如果你不知道包 - 只有类名,你可以尝试使用spring框架:
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”的类列表(它们可能不止一个!)。
然后更容易
expectedSuperclass.isAssignableFrom(yourClass);
答案 1 :(得分:1)
是的,反思就是答案:
Class barClass = Class.forName("some.package.Bar"); // will throw a ClassNotFoundException if Bar is not a valid class name
Class fooClass = some.package.Foo.class;
assert fooClass.isAssignableFrom(barClass); // true means Bar extends (or implements) Foo