rspec/rules/S6202/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
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.
2023-05-25 14:18:12 +02:00

70 lines
1.7 KiB
Plaintext
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

== 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[]