mardi 24 juillet 2018

Generate anonymous class from Class type

I have an interface in my code called Cache, which has several implementations:

public interface Cache {
    //...
}

I have a method called someMethod, which takes as input, an instance of Cache:

public void someMethod(Cache cache) {
    //...
}

Inside someMethod, I'd like to get the Class type of cache (can be any class implementing Cache), and create an anonymous class based on that type. Something like this:

public void someMethod(Cache cache) {
    Class type = cache.getClass();

    Cache newInstance = new type {
        //some new anonymous class methods here ...
    }
}

How can I do this ?

One obvious way of doing this is to have a switch case on type of cache and then create anonymous class of each type, but that would be ugly repetitive code.





Aucun commentaire:

Enregistrer un commentaire