
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
65 lines
1.7 KiB
Plaintext
65 lines
1.7 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)
|
|
|
|
=== Message
|
|
|
|
Use "isAssignableFrom" instead.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
``++instanceOf(clazz)++``
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 19 Jul 2016, 17:24:56 Ann Campbell wrote:
|
|
https://github.com/google/error-prone/blob/master/docs/bugpattern/IsInstanceOfClass.md
|
|
|
|
endif::env-github,rspecator-view[]
|