簡體   English   中英

如何在運行時獲取實現類型

[英]How to get the implementation type at runtime

我有一個名為 A 的 iterface。現在我從接口 A 派生 3 個類。

我如何向接口添加一些方法,例如 getType(),它返回我正在處理的正確類型的實例。 我不想在嵌套的 if else 中做類似 demo instanceOf A 之類的事情來檢查實例類型。

總是有.getClass()將返回對象的Class 但它本質上與instanceof相同。 您不需要知道具體類型。 而是將邏輯放在每個實現中。 例如:

interface Foo() {
     int calculate();
}

class Bar implements Foo {
     public int calculate() {
        return 1+1;
     }
}

class Baz implements Foo {
     public int calculate() {
        return 2+2;
     }
}

Foo foo = getFoo();
int result = foo.calculate();

代替:

Foo foo = getFoo();
int result = 0;
if (foo.getClass().equals(Bar.class)) {
    result = 1+1;
} else of (foo.getClass().equals(Baz.class)) {
    result = 2+2;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM