java 反射到接口,Java多接口和反射

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?

解决方案

What you really want is AND type -- A&B. This is generally not supported in Java. However, we could create a wrapper class that contains a value that is both type A and type B. (It seems that every problem can be solved by a wrapper:)

public class AB

{

public final T v;

...

v = (T)Class.forName("test.messages.X").newInstance();

}

Instead of using type A&B, we use AB> everywhere it's needed. We'll operate on its field v, which is both A and B.

void foo(AB> ab)

{

ab.v.methodOfA();

ab.v.methodOfB();

}

Or you could make AB a subtype of A and B too.

public class AB implements A, B

{

public final T v;

@Override // A

public int methodOfA(){ return v.methodOfA(); }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值