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

相關文章
相關標籤/搜索