简体   繁体   English

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

[英]How to access different attributes of different implementation of the same interface

I have an interface我有一个界面

public interface Inter {
    int interAttr = 0;   
}

And two classes that implements it, each one with an additional attribute and each one of different type.还有两个实现它的类,每个类都有一个附加属性,每个类都有不同的类型。

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

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

And I have list of Inter objects that are a mix of Impl1 and Impl2我有Impl1Impl2混合的Inter对象列表

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

Of course I can query i11.impl1Attr or impl21.impl2Attr in the body of the main But is there a way for me to have access to the attributes of the different implementations in the list in the for loop?当然,我可以在main的主体中查询i11.impl1Attrimpl21.impl2Attr但是有没有办法让我访问for循环中列表中不同实现的属性?

I'm probably oversimplifying the problem, but is instanceof + casting not an option?我可能过于简单化了这个问题,但是instanceof + cast 不是一个选项吗?

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM