Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To test whether <code>clazz</code> is a (sub) type of <code>MyClass</code> do</p> <pre><code>MyClass.class.isAssignableFrom(clazz) </code></pre> <p>From the javadoc for <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#isAssignableFrom%28java.lang.Class%29" rel="nofollow"><code>Class.isAssignableFrom</code></a></p> <blockquote> <p>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.</p> <p>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.</p> </blockquote> <p>So</p> <pre><code>Object.class.isAssignableFrom(String.class) </code></pre> <p>is true because each <code>String</code> is also an <code>Object</code> but</p> <pre><code>String.class.isAssignableFrom(Object.class) </code></pre> <p>is false because not all <code>Object</code>s are <code>String</code>s.</p> <hr> <p>The name "<code>isAssignableFrom</code>" comes from the fact that,</p> <pre><code>Class1 x = (Class2) null; </code></pre> <p>is only legal when</p> <pre><code>Class1.class.isAssignableFrom(Class2.class) </code></pre> <p>I.e., we can <strong>assign</strong> a field or variable with static type <code>Class1</code> a value that comes <strong>from</strong> an expression whose static type is <code>Class2</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload