Checking Java Object Hierarchy Externally

Say I have the string "Bar" and I want to know if Bar is a valid object, and in addition, "Bar" extends "Foo". Will I use Java reflection or is there a better way, like a database? and how would i do that?

Greetings

0
source share
2 answers

If you don't know the package - just the class name, you can try this using the 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 a list of classes called "Bar" (there may be several!).

Then easier

expectedSuperclass.isAssignableFrom(yourClass);
+1
source

Yes, reflection is 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
+1
source

Source: https://habr.com/ru/post/1727382/


All Articles