检查Java对象层次对外(Check Java Object Hierarchy Externall

2019-10-18 21:53发布

说我有字符串“bar”,我想知道是否酒吧是一个有效的对象,此外,“酒吧”是否延长“富”。 请问我可以用Java反射或是否有更好的办法,如数据库? 我会怎么做呢?

干杯

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

以上两种方法给你,被命名为“律师”的类的列表(它们可能不止一个!)。

然后,它更容易

expectedSuperclass.isAssignableFrom(yourClass);


Answer 2:

是的,反映的是答案:

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


文章来源: Check Java Object Hierarchy Externally