Class
/**
* Instances of the class Class represent classes and interfaces in a running Java application.
*
* Type parameters: <T> – the type of the class modeled by this Class object. For example, the type of String.class is Class<String>. Use Class<?> if the class being modeled is unknown.
*/
public final class Class<T> implements java.io.Serializable,
GenericDeclaration, Type, AnnotatedElement {}
Methods
isAssignableFrom()
/**
* Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of,
* the class or interface represented by the specified Class parameter
* Params: cls – the Class object to be checked
* Returns: the boolean value indicating whether objects of the type cls can be assigned to objects of this class
*
* X.class.isAssignableFrom(cls) ==> 判断 cls 类型的对象是否为 X 类型的实例
* 即判断 X 与 cls 所属的类/接口是否相同,或者 X 是 cls 的父类/父接口
*/
public native boolean isAssignableFrom(Class<?> cls);
示例:
// public final class String implements CharSequence {}
Class<String> stringClass = String.class;
Class<CharSequence> charSequenceClass = CharSequence.class;
boolean b = charSequenceClass.isAssignableFrom(stringClass); // true
boolean b2 = stringClass.isAssignableFrom(charSequenceClass); // false
isInstance()
/**
* Determines if the specified Object is assignment-compatible with the object represented by this Class.
* Params: obj – the object to check
* Returns: true if obj is an instance of this class
*/
public native boolean isInstance(Object obj);
示例:
/*
* X.class.isInstance(obj) ==> 判断 对象obj 是否可以作为X类的实例
* 等价:obj instanceof X
* 关键字 instanceof 更简洁,isInstance() 更灵活
*/
其他
类名.class vs 对象.getCalss()
public toString() {
return getClass().getName() +"@" + Integer.toHexString(hashCode());
}
网友评论