mardi 10 mars 2020

Instantiate an interface using java reflections?

Is it possible to instantiate an interface just using java reflections? I would like to have a factory method - producing interfaces, just by knowing its class.

public interface IReflection {

    public default String say(){
        return  "test default";
    }

}


public <T> T factoryProduce(Class<T> type){
    // how to instantiate on factoryProduce(IReflection.class)
}

I am trying to simulate the following using reflections. Because for the following I can not dynamically get the interface class

return new IReflection(){}

Using newInstance() failed, cause there is no constructor in the interface.

Constructor<?>[] con = IReflection.class.getDeclaredConstructors(); // empty
i = IReflection.class.newInstance();    // no constructor
i = IReflection.class.getDeclaredConstructor().newInstance(); // no constructor




Aucun commentaire:

Enregistrer un commentaire