samedi 5 mai 2018

Handle methods from given interface, return required result

Suppose I have a unknown interface, and I want to be able to construct an object which, when user calls some method from interface on it, returns something specified by that interface. E.g. having a Class class object, representing unknown Interface, I want to be able to construct an Object, which behaves like something which correctly implements that Interface. For instance, say I'm working on method

public <E> E myMethod(Class<E> class){
    ...
    return res;
}

Where class is representation of an unknown interface, let for instance

public <E> interface Writer{
    public String write(String s);
}
Class<E> class = Writer.class;

All I want now is that any call like

returnedFromMyMethod.write(s);

actually do the job, e.g. returns given string I know that there's reflection to be used, because all of that is going on in runtime, we don't know what exactly the interface is. But can't figure it out. Any ideas?





Aucun commentaire:

Enregistrer un commentaire