干饭人干饭时间,第一个冲向饭店!
1. 方法解读
将当前类转化为指定类的子类,用以窄化对象,在Java中我们判断一个类是否是另外一个类的实例对象通常使用instanceof,动态运行时我们会用Class.isInstance方法来判断对象和类之间是否能够相互转化。另外我们还有一个方法是asSubclass,它将一个类转换成另外一个的实例,如果转换异常就会抛出ClassCastException异常,也就是这个类不是另外一个类的实例;所以我们可以通过它抛出异常的方式来判断一个类是否是另外一个类的实例;
2. 源码分析
/**
* Casts this {@code Class} object to represent a subclass of the class
* represented by the specified class object. Checks that the cast
* is valid, and throws a {@code ClassCastException} if it is not. If
* this method succeeds, it always returns a reference to this class object.
*
* <p>This method is useful when a client needs to "narrow" the type of
* a {@code Class} object to pass it to an API that restricts the
* {@code Class} objects that it is willing to accept. A cast would
* generate a compile-time warning, as the correctness of the cast
* could not be checked at runtime (because generic types are implemented
* by erasure).
*
* @param <U> the type to cast this class object to
* @param clazz the class of the type to cast this class object to
* @return this {@code Class} object, cast to represent a subclass of
* the specified class object.
* @throws ClassCastException if this {@code Class} object does not
* represent a subclass of the specified class (here "subclass" includes
* the class itself).
* @since 1.5
*/
@SuppressWarnings("unchecked")
public <U> Class<? extends U> asSubclass(Class<U> clazz) {
if (clazz.isAssignableFrom(this))
return (Class<? extends U>) this;
else
throw new ClassCastException(this.toString());
}
- 概要
将当前Class对象转换成指定的Class对象,如果有当前的Class并非指定的Class的子类则抛出异常;常用于需要将一个Class对象窄化,以适应与某个API中的方法接受的参数。如果此方法成功,则它始终返回对此类对象的引用。失败则抛出ClassCastException 。 - 参数
Class<U> clazz
- 一个泛型类 - 结果
Class<? extends U>
- 继承参数类的类 - 异常
ClassCastException
- 如果此类对象不表示指定类的子类(包括类本身),则会抛出类转换异常。
3. 实例演示
public class Test {
public static void main(String[] args) {
class SuperClass {
}
class SubClass extends SuperClass {
}
Class<?> clazz = SubClass.class;
String name = clazz.getName();
try {
Class<?> SuperClass = clazz.asSubclass(SuperClass.class);
System.out.println(name + "是SuperClass的子类");
} catch (ClassCastException e) {
System.out.println(name + "不是SuperClass的子类");
}
}
}
................................................................
・【CONSOLE】実行結果
com.it.god.controller.Test$1SubClass是SuperClass的子类