Check Java Object Hierarchy Externally

2019-08-19 12:04发布

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?

Cheers

2条回答
做个烂人
2楼-- · 2019-08-19 12:15

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

The two above methods give you the list of classes that are named "Bar" (they may be more than one!).

Then it's easier

expectedSuperclass.isAssignableFrom(yourClass);
查看更多
小情绪 Triste *
3楼-- · 2019-08-19 12:17

Yes, reflection is the the answer:

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
查看更多
登录 后发表回答