instanceof
This keyword is mainly used to judge whether an object is an instance of a certain class.
For example, sometimes we want to process a dataset like this:
Map<String, Object> data = new HashMap<>();
data.put("key1", "aaa");
data.put("key2", 111);
The Value value in this Map may be different objects, so Object is defined. At this time, when we get it, we need to judge and convert it before processing it.
For example, if we take out key1
of value
and then intercept a string, we need to write:
Object value =data.get("key1");
if (value instanceof String) {
String s = (String) value;
System.out.println(s.substring(1));
}
First determine whether the obtained value is a String, and then do the forced type conversion, and then operate on the string. This is the traditional way of writing, and after the enhancement of Java 16, the judgment and type conversion of instanceof
can be combined into one, so the improved writing can be as follows:
Object value =data.get("key1");
if (value instanceof String s) {
System.out.println(s.substring(1));
}
Isn't it much simpler? If you haven't used it before, give it a try!
Tips: This feature has gone through 2 Preview versions (JEP 305 in JDK 14, JEP 375 in JDK 15), and is finally finalized in JEP 394 in JDK 16.
If you encounter difficulties in the learning process? You can join our high-quality technical exchange group , participate in exchanges and discussions, and learn and progress better! Also, don't walk away, follow me! Continue to update the new Java feature column !
Welcome to my public account: Programmer DD. Learn about cutting-edge industry news for the first time, share in-depth technical dry goods, and obtain high-quality learning resources
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。