[英]Using instanceof to test interfaces
I've been having a bit of trouble with this problem. 我在这个问题上有点麻烦。 The question:
问题:
Write a complete Java program that does the following: 编写一个完整的Java程序,该程序执行以下操作:
So this is what I've come up with so far: 因此,这是我到目前为止提出的:
public interface I1
{
}
public interface I2
{
}
public interface I3 extends I1, I2
{
}
public interface I4
{
}
public class W extends X implements I4
{
}
I'm having a bit of confusion with the InstanceofTest method. 我对InstanceofTest方法有些困惑。 I know that the instanceof operator would tell you if a certain object is an instance of a certain type, like when you do it like this:
我知道instanceof运算符会告诉您某个对象是否是某种类型的实例,例如当您这样做时:
public class InstanceofTest
{
public static void main(String[] args)
{
W w = new W();
if (w instanceof X)
{
System.out.println("w is an instance of X.");
}
}
}
The problem I'm having is using instanceof
to see if w implements each of the interfaces. 我遇到的问题是使用
instanceof
来查看w是否实现了每个接口。 I have no idea how I would go about doing that. 我不知道该怎么做。 Any help would be greatly appreciated!
任何帮助将不胜感激!
Edit: So, should I do it like this? 编辑:那么,我应该这样做吗?
public class InstanceofTest
{
public static void main(String[] args)
{
W w = new W();
if (w instanceof X)
{
System.out.println("w is an instance of X.");
}
if (w instanceof I1)
{
System.out.println("w implements I1.");
}
if (w instanceof I2)
{
System.out.println("w implements I2.");
}
if (w instanceof I3)
{
System.out.println("w implements I3.");
}
if (w instanceof I4)
{
System.out.println("w implements I4.");
}
}
}
Well, here is the full solution for you: 好吧,这是为您提供的完整解决方案:
public interface I1 {}
public interface I2 {}
public interface I3 extends I1, I2 {}
public interface I4 {}
public class X implements I3 {}
public class W extends X implements I4 {}
public class InstanceofTest {
public static void main(String[] args){
W w = new W();
if (w instanceof I1)
System.out.println("W implements I1");
if (w instanceof I2)
System.out.println("W implements I2");
if (w instanceof I3)
System.out.println("W implements I3");
if (w instanceof I4)
System.out.println("W implements I4");
if (w instanceof X)
System.out.println("W extends X");
}
}
And the result will be that W
implements every interface and extends X
. 结果将是
W
实现每个接口并扩展X
将这些接口像Set<Class> classes
一样存储在Collection
,然后对其进行迭代并与您的对象进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.