开发者

Check Java Object Hierarchy Externally

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 databas开发者_开发百科e? and how would I do it?

Cheers


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜