Java多接口和反射 [英] Java multiple interfaces and reflection
问题描述
我有一个名为X的类,它实现了多个(例如3个)接口,称之为A,B和C.
I have a class called X that implements multiple (e.g. 3) interfaces, call them A, B and C.
我创建另一个扩展接口A的接口AB和B。
I create another interface AB that extends interface A and B.
如何使用反射创建可分配给接口AB的X实例?
How can I use reflection to create an instance of X that is assignable to interface AB?
我一直使用此代码获取ClassCast异常:
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);
现在当我尝试使用一个界面时,说A,它可以正常工作。
Now when I try with just one interface, say A, it works fine.
无论如何都可以使用组合界面AB吗?
Is there anyway to get it to work with the combined interface AB?
推荐答案
什么你真正想要的是 AND type - A& B
。 Java中通常不支持此操作。但是,我们可以创建一个包含类型A和类型B的包装类。(似乎每个问题都可以通过包装器解决:)
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<T extends A&B>
{
public final T v;
...
v = (T)Class.forName("test.messages.X").newInstance();
}
而不是使用类型 A& B
,我们在需要的任何地方使用 AB<?>
。我们将在其 v
的字段上操作,这是 A
和 B
。
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();
}
或者你可以赚 AB
A和B的子类型。
Or you could make AB
a subtype of A and B too.
public class AB<T extends A&B> implements A, B
{
public final T v;
@Override // A
public int methodOfA(){ return v.methodOfA(); }
在 https://stackoverflow.com/a/32659085/2158288
这篇关于Java多接口和反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!