gpt4 book ai didi

java - 如何访问同一接口(interface)的不同实现的不同属性

转载 作者:行者123 更新时间:2023-12-01 16:40:00 25 4
gpt4 key购买 nike

我有一个界面

public interface Inter {
int interAttr = 0;
}

以及两个实现它的类,每个类都有一个附加属性,并且每个类都有不同的类型。

@AllArgsConstructor
public class Impl1 implements Inter {
public int impl1Attr;
}

@AllArgsConstructor
public class Impl2 implements Inter {
public String impl2Attr;
}

我有 Inter 对象列表,它们是 Impl1Impl2 的混合体

public class main {
public static void main(String[] args) {
Impl1 i11 = new Impl1(0);
Impl1 i12 = new Impl1(1);
Impl2 i21 = new Impl2("zero");
Impl2 i22 = new Impl2("one");
List<inter> implList = new ArrayList<Inter>();
implList.add(i11);
implList.add(i12);
implList.add(i21);
implList.add(i22);
for (Inter el : implList){
// this of course works
int a = el.interAttr1;
// But how do I get access to impl1Attr and impl2Attr?
}
}
}

当然,我可以在main正文中查询i11.impl1Attrimpl21.impl2Attr但是有没有办法让我访问 for 循环中列表中不同实现的属性?

最佳答案

我可能过于简单化了问题,但是instanceof + 类型转换不是一个选项?

for (Inter el : implList) {

int a = el.interAttr;

if (el instanceof Impl1)
System.out.println(((Impl1)el).impl1Attr);

if (el instanceof Impl2)
System.out.println(((Impl2)el).impl2Attr);
}

关于java - 如何访问同一接口(interface)的不同实现的不同属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61876593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com