dimanche 12 novembre 2017

Call Class newInstance on nth degree subclass

I have to instantiate an object but being from user input, I will not know which subclass it will be. I am also not guaranteed instantiation due to threading (even when thread safe, threads can have contrary directives add/delete the same object). The issue comes with getting and printing a structure, as a user may enter a request to modify an object that is no longer there.

For this reason I have chosen to instantiate objects with reflection using generic classes wrapped in a synchronization block that locks on that specific structure.To do this, I have to instantiate the concrete subclass 2 levels from the abstract grandparent class.

Here's an example of what I am trying to do:

public <T> Class<T> makeGrandparent(Class<T> c){
    Object child = null;
    try{
        child = (Class<? extends (? extends T)).newInstance();
    } catch(/*Exceptions*/){}
    finally {
        return child;
    }
}

Is there a way to instantiate lower subclasses of a generic class? Or can you only instantiate the direct child of a parent class?





Aucun commentaire:

Enregistrer un commentaire