Last active
March 20, 2018 07:09
-
-
Save li2/e2e2aa7cb0aea5ec994d to your computer and use it in GitHub Desktop.
[如何判断某个对象是否继承自某类? How to determine an object's class (in Java)?]
http://stackoverflow.com/questions/541749/how-to-determine-an-objects-class-in-java #tags: java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Method #0:操作符(或者说关键字)instanceof | |
* object 是 C 的实例吗? | |
*/ | |
if (object instanceof C) | |
; | |
/** | |
* Method #1: isInstance(Object object) | |
* Tests whether the given object can be cast to the class represented by this Class. | |
* This is the runtime version of the instanceof operator. | |
* | |
* @return true if object can be cast to the type represented by this Class; | |
* false if object is null or cannot be cast. | |
* | |
* 方法 isInstance() 和操作符 instanceof 作用一致。 | |
* object 是 C 的实例吗?阅读顺序是反的,应该是为了方便定义 API 吧。 | |
* 而 instanceof 更符合阅读的顺序。 | |
*/ | |
if (C.class.isInstance(object)) | |
; | |
/** | |
* 向上转型(Upcasting):从导出类转型为基类。 | |
* 向上转型总是安全的,因为导出类是基类的一个超集。《Thinking in Java》7.7.1 | |
*/ | |
// Method #2 | |
/** | |
* getClass(): Returns the unique instance of Class that represents this object's class. | |
* may throw NullPointerException | |
*/ | |
if (obj.getClass().equals(C.class)) | |
; | |
// Method #3 | |
/** | |
* isAssignableFrom(Class<?> c): Can c be assigned to this class? For example, | |
* | |
* String can be assigned to Object (by an upcast), however, | |
* an Object cannot be assigned to a String as a potentially | |
* exception throwing downcast would be necessary. Similarly for interfaces, | |
* | |
* a class that implements (or an interface that extends) another | |
* can be assigned to its parent, but not vice-versa(反之亦然). | |
* | |
* All Classes may assign to themselves. | |
* Classes for primitive types may not assign to each other. | |
*/ | |
if (C.class.isAssignableFrom(obj.getClass())) | |
; | |
/** null is not an instance of any type, but it can be cast to any type. */ | |
// Method #4 | |
try { | |
C c = (C) obj; | |
// No exception: obj is of type C or IT MIGHT BE NULL! | |
} catch (ClassCastException e) { | |
} | |
// Method #5 | |
try { | |
C c = C.class.cast(obj); | |
// No exception: obj is of type C or IT MIGHT BE NULL! | |
} catch (ClassCastException e) { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment