簡體   English   中英

如何訪問同一接口的不同實現的不同屬性

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

我有一個界面

public interface Inter {
    int interAttr = 0;   
}

還有兩個實現它的類,每個類都有一個附加屬性,每個類都有不同的類型。

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

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

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

當然,我可以在main的主體中查詢i11.impl1Attrimpl21.impl2Attr但是有沒有辦法讓我訪問for循環中列表中不同實現的屬性?

我可能過於簡單化了這個問題,但是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