如何访问同一接口的不同实现的不同属性?

问题描述 投票:0回答:1

我有一个接口

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?
        }
    }
}

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

java list interface implements mixed-type
1个回答
0
投票

我可能把问题过于简单化了,但是我的问题是 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);
}
© www.soinside.com 2019 - 2024. All rights reserved.