Is there something like instanceOf(Class c) in Java?

When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime.

 

instanceof can only be used with reference types, not primitive types. isAssignableFrom() can be used with any class objects:

a instanceof int  // syntax error
3 instanceof Foo  // syntax error
int.class.isAssignableFrom(int.class)  // true

See http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isAssignableFrom(java.lang.Class).

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *