vendredi 22 janvier 2016

Detecting Class object equivalence for classes loaded by different ClassLoaders

My Task is to write a unit test for a method findSubClassImplementation that returns an instance for a given Class object. The method signature looks like this:

public <T extends SuperClass> T findSubClassImplementation(Class<T> cls) throws Exception 

Internally the method checks wether the supplied Class object belongs to a set of known classes and then returns an instance of that class:

if (Subclass.class.equals(cls)) 
        return (T) new Subclass(args);

If the class is not known, an Exception is thrown.

I tried to load all Classes inheriting from SuperClass via Reflection, however when I pass them as argument to the method, an exception is thrown: The method does not recognize them.

I assume what happens is this: Class does not implement equals, thus equals of Object is used, that compares with "==". As reflection uses a different ClassLoader than is used in findSubClassImplementation the two class Objects are different.

Is it possible to get the other Class object for a class that I have loaded with Reflection? Do you have another idea how to deal with this problem?





Aucun commentaire:

Enregistrer un commentaire