Class.isAssignableFrom(Class cls)理解

 1. 方法理解

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. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.html

Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class 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.java

 这个Class对象(能够是class或者interface)是不是参数Class(能够是class或者interface)的同类型、或者超类、或者超接口。若是这个Class对象表示一个原生类型,仅在参数Class与这个Class是相同类型时返回true。web

Java赋值语句中,‘=’能够这样理解,‘=’左边的变量被‘=’右边的对象指派,或者说‘=’右边的对象指派给‘=’左边的变量。spring

Parent p = new Child();api

    assign from
   ------------>oracle

    assign to
   <------------ide

因此从Class1.isAssignableFrom(Class2<?> cls)方法名可知,方法断定Class1是否能够被Class2指派,即:this

Class1 c = new Class2()赋值语句是否成立,具体说,就是Class2是否能够向上类型转换到Class1spa

2. 方法应用

在Spring与ServletContainer集成时,ContextLoader(spring-web-4.1.4.RELEASE)建立WebApplicationContext方法中,在BeanUtils实例话contextClass以前,判断了配置的contextClass是不是ConfigurableWebApplicationContext的子类型。code

org.springframework.web.context.ContextLoader#createWebApplicationContext(ServletContext sc)
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
		Class<?> contextClass = determineContextClass(sc);
        // contextClass默认是org.springframework.web.context.support.XmlWebApplicationContext
		if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
			throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
					"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
		}
		return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
	}

3. 参考

https://docs.oracle.com/javase/8/docs/api/

https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.1

相关文章
相关标签/搜索