rspec/rules/S6202/java/rule.adoc

49 lines
1.4 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02: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 developement, 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.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
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;
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
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
}
----