download: be based on Vue3 Create front desk + Zhongtai general efficiency improvement solution ( Network disk link )
Java 16 New characteristics :instanceof To strengthen
instanceof Keyword , It is mainly used to judge whether an object is an instance of a class .
example , Sometimes we have to deal with a data set similar to this :
Map<String, Object> data = new HashMap<>();
data.put("key1", "aaa");
data.put("key2", 111);
Copy code
This Map Medium Value Because values can be different objects , So the definition is Object. This time , When we get When I came out , Judge and convert the needs before handling them .
example , Let's take out key1 Of value, Then the operation of intercepting a string , Just write it like this :
Object value =data.get("key1");
if (value instanceof String) {
String s = (String) value;
System.out.println(s.substring(1));
}
Copy code
First identify the obtained value Can it be String, Then do forced type conversion , Then stop the operation on the string . This is the traditional way of writing , And in the Java 16 After the strengthening of , About instanceof Discrimination and type conversion can be combined into one , Therefore, the improved writing method can be as follows :
Object value =data.get("key1");
if (value instanceof String s) {
System.out.println(s.substring(1));
}
Copy code
Isn't it much simpler ? If you haven't used it , Try the operation quickly !
Tips: This function has experienced 2 individual Preview edition (JDK 14 Medium JEP 305、JDK 15 Medium JEP 375), Finalized on JDK 16 Medium JEP 394.