开发者

How to get the implementation type at runtime

I have a iterface called A. Now i开发者_JS百科 derive 3 classes from interface A.

How i can i add some method to the interface like getType() which return me the right type of instance I am dealing with. I don't want to do something like demo instanceOf A in nested if else for checking the instance type.


There's always .getClass() which will return the object's Class. But it is essentially the same as instanceof. You should not need to know the concrete type. Put the logic in each implementation instead. So for example:

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

instead of:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜