50 lines
1.2 KiB
Plaintext
50 lines
1.2 KiB
Plaintext
In Java 16, the feature "Pattern matching for instanceof" is finalized and can be used in production. Previously developers needed to do 3 operations in order to do this: check the variable type, cast it and assign the casted value to the new variable. This approach is quite verbose and can be replaced with pattern matching for ``++instanceof++``, doing these 3 actions (check, cast and assign) in one expression.
|
||
|
||
|
||
This rule raises an issue when an ``++instanceof++`` check followed by a cast and an assignment could be replaced by pattern matching.
|
||
|
||
|
||
== Noncompliant Code Example
|
||
|
||
[source,java]
|
||
----
|
||
int f(Object o) {
|
||
if (o instanceof String) { // Noncompliant
|
||
String string = (String) o;
|
||
return string.length();
|
||
}
|
||
return 0;
|
||
}
|
||
----
|
||
|
||
|
||
== Compliant Solution
|
||
|
||
[source,java]
|
||
----
|
||
int f(Object o) {
|
||
if (o instanceof String string) { // Compliant
|
||
return string.length();
|
||
}
|
||
return 0;
|
||
}
|
||
----
|
||
|
||
|
||
== See
|
||
|
||
* https://openjdk.java.net/jeps/394[JEP 394: Pattern Matching for instanceof]
|
||
|
||
|
||
ifdef::env-github,rspecator-view[]
|
||
|
||
'''
|
||
== Implementation Specification
|
||
(visible only on this page)
|
||
|
||
include::message.adoc[]
|
||
|
||
include::highlighting.adoc[]
|
||
|
||
endif::env-github,rspecator-view[]
|