简体   繁体   中英

How to get the implementation type at runtime

I have a iterface called A. Now i 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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