This is an enhancement of Java language with pattern matching for the instanceof operator. Currently, this feature is in the second preview in JDK 15.
So currently when we need to cast an object, we check it using instanceof operation then only we cast the object to save our self from class cast exception.
In the above code snippet, we have to explicitly cast it to an object.
In this enhancement, we no more have to do it.
To run the below code you need to install JDK 14 or above and have to enable the preview feature of javac & java.
In order to enable that preview feature.
javac
--enable-preview
-release <version>
<Source file>
java
--enable-preview
<Compiled class>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Anindya Bandopadhyay (anindyabandopadhyay@gmail.com) | |
public class PatternMatchingOfInstance { | |
public static void main(final String args[]) { | |
PatternMatchingOfInstance instance = new PatternMatchingOfInstance(); | |
Object obj = instance.getValue((instance.new IntValue(1))); | |
if(obj instanceof Integer) { | |
final Integer intValue = (Integer) obj; | |
System.out.println(String.format("Int value = %d", intValue)); | |
} | |
//JEP 375: Pattern Matching for instanceof (Second Preview) | |
if(obj instanceof Integer objInt) { | |
System.out.println(String.format("Using Pattern Matching for instanceof: Int value = %d", objInt)); | |
} | |
} | |
private Object getValue(final Value value) { | |
return value.getValue(); | |
} | |
interface Value { | |
Object getValue(); | |
} | |
class IntValue implements Value { | |
private final int value; | |
public IntValue(final int value) { | |
this.value = value; | |
} | |
@Override | |
public Integer getValue() { | |
return value; | |
} | |
} | |
class BoolValue implements Value { | |
private final boolean value; | |
public BoolValue(final boolean value) { | |
this.value = value; | |
} | |
@Override | |
public Boolean getValue() { | |
return value; | |
} | |
} | |
class StrValue implements Value { | |
private final String value; | |
public StrValue(final String value) { | |
this.value = value; | |
} | |
@Override | |
public String getValue() { | |
return value; | |
} | |
} | |
class DoubleValue implements Value { | |
private final double value; | |
public DoubleValue(final double value) { | |
this.value = value; | |
} | |
@Override | |
public Double getValue() { | |
return value; | |
} | |
} | |
class FloatValue implements Value { | |
private final float value; | |
public FloatValue(final float value) { | |
this.value = value; | |
} | |
@Override | |
public Float getValue() { | |
return value; | |
} | |
} | |
} |