57 lines
1.6 KiB
Plaintext
57 lines
1.6 KiB
Plaintext
== Why is this an issue?
|
|
|
|
The ``++Class.isInstance++`` method is the dynamic equivalent of the ``++instanceof++`` operator. According to the JavaDoc, ``++isInstance++``
|
|
|
|
|
|
____
|
|
returns ``++true++`` if the specified Object argument is an instance of the represented class (or of any of its subclasses); it returns ``++false++`` otherwise
|
|
|
|
____
|
|
|
|
|
|
Thus, calling ``++isInstance++`` with a class argument is likely a mistake, since any random ``++Class++`` will only be "an instance of the represented class" when the left-hand side of the call is ``++Class.class++`` itself. To test for a class/sub-class relationship, use ``++isAssignableFrom++`` instead.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
Class<Number> num = Number.class;
|
|
Class<BigInteger> bi = BigInteger.class;
|
|
|
|
System.out.println(num.isInstance(bi)); // Noncompliant. false
|
|
System.out.println(bi.isInstance(Class.class)); // Noncompliant. false
|
|
System.out.println(Class.class.isInstance(bi)); // Noncompliant. true
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
Class<Number> num = Number.class;
|
|
Class<BigInteger> bi = BigInteger.class;
|
|
|
|
System.out.println(num.isAssignableFrom(bi)); // true
|
|
System.out.println(bi.isAssignableFrom(Class.class)); // false
|
|
System.out.println(Class.class.isAssignableFrom(bi)); // false
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
include::highlighting.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|