lundi 11 janvier 2016

Java multiple interfaces and reflection

I have a class called X that implements multiple (e.g. 3) interfaces, call them A, B and C.

I create another interface AB that extends interface A and B.

How can I use reflection to create an instance of X that is assignable to interface AB?

I keep getting ClassCast exceptions with this code:

package test.messages;

public interface A
{
    void methodA();
}

package test.messages;

public interface B
{
    void methodB();
}

package test.messages;

public interface C
{
    void methodC();
}

package test.messages;

public interface AB extends A, B
{

}

package test.messages;

public class X implements A, B, C
{
    @Override
    public void methodC()
    {
        System.out.println("C");
    }

    @Override
    public void methodB()
    {
        System.out.println("B");
    }

    @Override
    public void methodA()
    {
        System.out.println("A");
    }
}

Then in a completely different class:

AB api = (AB)Class.forName("test.messages.X").newInstance();

System.out.println(api);

Now when I try with just one interface, say A, it works fine.

Is there anyway to get it to work with the combined interface AB?





Aucun commentaire:

Enregistrer un commentaire