
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.
70 lines
1.7 KiB
Plaintext
70 lines
1.7 KiB
Plaintext
== Why is this an issue?
|
||
|
||
The ``++instanceof++`` construction is a preferred way to check whether a variable can be cast to some type statically because a compile-time error will occur in case of incompatible types. The method https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#isInstance-java.lang.Object-[isInstance()] from ``++java.lang.Class++`` works differently and does type check at runtime only, incompatible types will therefore not be detected early in the development, potentially resulting in dead code. The ``++isInstance()++`` method should only be used in dynamic cases when the ``++instanceof++`` operator can't be used.
|
||
|
||
|
||
This rule raises an issue when ``++isInstance()++`` is used and could be replaced with an ``++instanceof++`` check.
|
||
|
||
|
||
=== Noncompliant code example
|
||
|
||
[source,java]
|
||
----
|
||
int f(Object o) {
|
||
if (String.class.isInstance(o)) { // Noncompliant
|
||
return 42;
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
int f(Number n) {
|
||
if (String.class.isInstance(n)) { // Noncompliant
|
||
return 42;
|
||
}
|
||
return 0;
|
||
}
|
||
----
|
||
|
||
|
||
=== Compliant solution
|
||
|
||
[source,java]
|
||
----
|
||
int f(Object o) {
|
||
if (o instanceof String) { // Compliant
|
||
return 42;
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
int f(Number n) {
|
||
if (n instanceof String) { // Compile-time error
|
||
return 42;
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
boolean fun(Object o, String c) throws ClassNotFoundException
|
||
{
|
||
return Class.forName(c).isInstance(o); // Compliant, can't use instanceof operator here
|
||
}
|
||
----
|
||
|
||
ifdef::env-github,rspecator-view[]
|
||
|
||
'''
|
||
== Implementation Specification
|
||
(visible only on this page)
|
||
|
||
=== Message
|
||
|
||
Replace this usage of 'A.class.isInstance()' with 'instanceof A'
|
||
|
||
|
||
=== Highlighting
|
||
|
||
isInstance() invocation
|
||
|
||
|
||
endif::env-github,rspecator-view[]
|