rspec/rules/S6202/java/rule.adoc

70 lines
1.7 KiB
Plaintext
Raw Permalink Normal View History

== Why is this an issue?
2022-05-12 06:20:51 -04:00
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.
2021-04-28 16:49:39 +02:00
This rule raises an issue when ``++isInstance()++`` is used and could be replaced with an ``++instanceof++`` check.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
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[]