views:

57

answers:

2

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

+1  A: 

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);
Bozho
+1  A: 

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
David Rabinowitz