isAssignableFrom, Extends/Implements
In Java Reflect API, in .isAssignableFrom methods in Class has its javadocs saying that it will return true 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".
The question is whether .isAssignableFrom will return true if on a class that implements Interface, or it only returns true when "extends" is used? In other words, what will happen and why in case:
public class MyClass implements MyInterface{}
MyInterface.isAssignable(MyClass.class) == false/true ?
It returns true
.
That are two ways to tell this from the Javadoc:
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
The term superinterface is defined in the Java Language Specification as follows:
The optional implements clause in a class declaration lists the names of interfaces that are direct superinterfaces of the class being declared.
Therefore, MyInterface
is a superinterface of MyClass
, and therefore MyInterface.class.isAssignableFrom(MyClass.class)
is true.
The other way to tell is the next paragraph of the javadoc:
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.
which matches because
MyInterface i = new MyClass();
compiles.
链接地址: http://www.djcxy.com/p/57414.html上一篇: 使用APNS PHP获取错误