转载链接:http://www.yiibai.com/javalang/class_isassignablefrom.html
关于java.lang.Class.isAssignableFrom()方法
描述
确定如果此Class对象所表示的类或接口是否相同,或者是一个超类或超指定的Class参数所表示的类或接口。
声明
以下是java.lang.Class.isAssignableFrom()方法的声明
public boolean isAssignableFrom(Class<?> cls)
参数
cls -- This is the Class object to be checked.
返回值
此方法返回布尔值,指示对象是否可以被分配到这个类的对象的类型CLS。
异常
NullPointerException -- if the specified Class parameter is null.
实例
下面的例子说明了如何使用java.lang.Class.isAssignableFrom()方法。
package com.yiibai;
import java.lang.*;
public class ClassDemo {
public static void main(String[] args) {
try {
ClassDemo cls = new ClassDemo();
Class c = cls.getClass();
// class object associated with BaseClass
Class bClass = BaseClass.class;
// checks whether BaseClass is assignable from ClassDemo
boolean retval = bClass.isAssignableFrom(c);
System.out.println("Return Value = " + retval);
// checks whether ClassDemo is assignable from BaseClass
retval = c.isAssignableFrom(bClass);
System.out.println("Return Value = " + retval);
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
// base class
class BaseClass extends ClassDemo {
public BaseClass() {
// no argument constructor
}
}
让我们来编译和运行上面的程序,这将产生以下结果:
Return Value = false
Return Value = true
补充
以下节选自 JDK 7 API
节选链接:http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html
-
isAssignableFrom
public boolean isAssignableFrom(Class<?> cls)
Determines if the class or interface represented by thisClass
object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specifiedClass
parameter. It returnstrue
if so; otherwise it returnsfalse
. If thisClass
object represents a primitive type, this method returnstrue
if the specifiedClass
parameter is exactly thisClass
object; otherwise it returnsfalse
.Specifically, this method tests whether the type represented by the specified
Class
parameter can be converted to the type represented by thisClass
object via an identity conversion or via a widening reference conversion. See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.-
Parameters:
-
cls
- theClass
object to be checked
Returns:
-
the
boolean
value indicating whether objects of the typecls
can be assigned to objects of this class
Throws:
-
NullPointerException
- if the specified Class parameter is null.
Since:
- JDK1.1
-
补充
补充链接:http://getspring.blog.163.com/blog/static/11530060920108854936934/
1,Class.isAssignableFrom(Class cls) 判定此 Class 对象所表示的类或接口与指定的 Class 参数cls所表示的类或接口是否相同,或是否是其超类或(超)接口,如果是则返回 true,否则返回 false。
2,instanceof 是用来判断一个对象实例是否是一个类或接口或其子类子接口的实例。
格式是: oo instanceof TypeName
interImpl instanceof inter
第一个参数是对象实例名,第二个参数是具体的类名或接口名,例如 String,InputStream。