Skip to content

Commit b963059

Browse files
authored
[BAEL-7817] Java 22 intro (#16454)
1 parent 5a87496 commit b963059

15 files changed

+341
-0
lines changed
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
<parent>
7+
<groupId>com.baeldung.core-java-modules</groupId>
8+
<artifactId>core-java-modules</artifactId>
9+
<version>0.0.1-SNAPSHOT</version>
10+
</parent>
11+
12+
<artifactId>core-java-22</artifactId>
13+
14+
15+
<properties>
16+
<maven.compiler.source>22</maven.compiler.source>
17+
<maven.compiler.target>22</maven.compiler.target>
18+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
19+
<java.version>22</java.version>
20+
</properties>
21+
<build>
22+
<plugins>
23+
<plugin>
24+
<groupId>org.apache.maven.plugins</groupId>
25+
<artifactId>maven-compiler-plugin</artifactId>
26+
<configuration>
27+
<source>22</source>
28+
<target>22</target>
29+
<compilerArgs>--enable-preview</compilerArgs>
30+
</configuration>
31+
</plugin>
32+
</plugins>
33+
</build>
34+
35+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
void main() {
2+
System.out.println("This is an implicitly declared class without any constructs");
3+
4+
int x = 165;
5+
int y = 100;
6+
7+
System.out.println(y + x);
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.baeldung.javafeatures;
2+
3+
public class MainApp {
4+
public static void main(String[] args) {
5+
System.out.println("Hello");
6+
MultiFileExample mm = new MultiFileExample();
7+
mm.ping(args[0]);
8+
}
9+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.javafeatures;
2+
3+
import static java.lang.foreign.FunctionDescriptor.*;
4+
5+
import java.lang.foreign.Arena;
6+
import java.lang.foreign.FunctionDescriptor;
7+
import java.lang.foreign.Linker;
8+
import java.lang.foreign.MemorySegment;
9+
import java.lang.foreign.SymbolLookup;
10+
import java.lang.foreign.ValueLayout;
11+
import java.lang.invoke.MethodHandle;
12+
13+
public class MemoryAPIExample {
14+
public long getLengthUsingNativeMethod(String string) throws Throwable {
15+
SymbolLookup stdlib = Linker.nativeLinker().defaultLookup();
16+
MethodHandle strlen =
17+
Linker.nativeLinker()
18+
.downcallHandle(
19+
stdlib.find("strlen").orElseThrow(),
20+
of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
21+
22+
try (Arena offHeap = Arena.ofConfined()) {
23+
MemorySegment str = offHeap.allocateFrom(string);
24+
25+
long len = (long) strlen.invoke(str);
26+
System.out.println("Finding String length using strlen function: " + len);
27+
return len;
28+
}
29+
}
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.baeldung.javafeatures;
2+
3+
public class MultiFileExample {
4+
public void ping(String s) {
5+
System.out.println("Ping from Second File " + s);
6+
}
7+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.baeldung.javafeatures;
2+
3+
import java.util.Random;
4+
5+
public class ScopedValueExample {
6+
public final static ScopedValue<User> LOGGED_IN_USER = ScopedValue.newInstance();
7+
8+
public void serve(Request request) {
9+
User loggedInUser = authenticateUser(request);
10+
ScopedValue.where(LOGGED_IN_USER, loggedInUser)
11+
.run(() -> processRequest(request));
12+
}
13+
14+
private User authenticateUser(Request request) {
15+
return new User(new Random().nextInt(100), STR."User\{new Random().nextInt()}");
16+
}
17+
18+
private void processRequest(Request request) {
19+
System.out.println("Processing request :: " + ScopedValueExample.LOGGED_IN_USER.get()
20+
.toString());
21+
}
22+
}
23+
24+
class User {
25+
private int id;
26+
private String userName;
27+
28+
public User(int id, String userName) {
29+
this.id = id;
30+
this.userName = userName;
31+
}
32+
33+
public String toString() {
34+
return STR."User :: \{this.id}";
35+
}
36+
}
37+
38+
class Request {
39+
40+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.javafeatures;
2+
3+
import java.util.List;
4+
import java.util.stream.Gatherers;
5+
6+
public class StreamGatherersExample {
7+
public List<List<String>> gatherIntoWindows(List<String> countries) {
8+
List<List<String>> windows = countries.stream()
9+
.gather(Gatherers.windowSliding(3))
10+
.toList();
11+
return windows;
12+
}
13+
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.baeldung.javafeatures;
2+
3+
import static java.lang.StringTemplate.STR;
4+
5+
import java.sql.Connection;
6+
import java.sql.DriverManager;
7+
import java.sql.SQLException;
8+
import java.util.ArrayList;
9+
import java.util.HashMap;
10+
import java.util.List;
11+
import java.util.Map;
12+
import java.util.logging.Logger;
13+
14+
public class UnnamedExpressions {
15+
private Logger LOGGER = Logger.getLogger(String.valueOf(UnnamedExpressions.class));
16+
17+
public int unnamedExpressionExampleUsingException(int someNumber) {
18+
int divided = 0;
19+
try {
20+
divided = someNumber / 0;
21+
} catch (ArithmeticException _) {
22+
System.err.println("Division by zero");
23+
}
24+
return divided;
25+
}
26+
27+
public Object unnamedExpressionsExampleUsingSwitch(Object obj) {
28+
switch (obj) {
29+
case Integer _ -> System.out.println("Is an integer");
30+
case Float _ -> System.out.println("Is a float");
31+
case String _ -> System.out.println("Is a String");
32+
default -> System.out.println("Default");
33+
}
34+
;
35+
return obj;
36+
}
37+
38+
public boolean unnamedExpressionForTryWithResources() {
39+
String url = "localhost";
40+
String user = "user";
41+
String pwd = "password";
42+
try (Connection _ = DriverManager.getConnection(url, user, pwd)) {
43+
LOGGER.info(STR."""
44+
DB Connection successful
45+
URL = \{url}
46+
usr = \{user}
47+
pwd = \{pwd}""");
48+
} catch (SQLException e) {
49+
LOGGER.warning("Exception");
50+
}
51+
return true;
52+
}
53+
54+
public Map<String, List<String>> unnamedExpressionForLambda() {
55+
Map<String, List<String>> map = new HashMap<>();
56+
map.computeIfAbsent("v1", _ -> new ArrayList<>())
57+
.add("0.1");
58+
return map;
59+
}
60+
61+
}
62+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.baeldung.javafeatures.classfile;
2+
3+
import java.io.IOException;
4+
import java.lang.classfile.ClassElement;
5+
import java.lang.classfile.ClassFile;
6+
import java.lang.classfile.ClassModel;
7+
import java.lang.classfile.MethodModel;
8+
import java.nio.file.Files;
9+
import java.nio.file.Path;
10+
11+
public class ClassFileDriver {
12+
public Path updateClass() throws IOException {
13+
final String PREFIX = "test_";
14+
final Path PATH = Path.of("src/main/java/com/baeldung/javafeatures/classfile/ClassFileExample.class");
15+
ClassFile cf = ClassFile.of();
16+
ClassModel classModel = cf.parse(PATH);
17+
byte[] newBytes = cf.build(classModel.thisClass().asSymbol(), classBuilder -> {
18+
for (ClassElement ce : classModel) {
19+
if (!(ce instanceof MethodModel mm && mm.methodName()
20+
.stringValue()
21+
.startsWith(PREFIX))) {
22+
classBuilder.with(ce);
23+
}
24+
}
25+
});
26+
return Files.write(PATH, newBytes);
27+
}
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.baeldung.javafeatures.classfile;
2+
3+
public class ClassFileExample {
4+
public void doSomething() {
5+
System.out.println("Do something here");
6+
}
7+
8+
public void doSomething2() {
9+
System.out.println("Do something here as well");
10+
}
11+
12+
public void test_something() {
13+
System.out.println("Test method");
14+
}
15+
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.baeldung.javafeatures.shapes;
2+
3+
public class Circle extends Shape {
4+
int sides;
5+
int length;
6+
7+
Circle(int sides, int length) {
8+
if (sides != 0 && length > 0) {
9+
throw new IllegalArgumentException("Cannot form circle");
10+
}
11+
super(sides, length);
12+
}
13+
14+
@Override
15+
int getArea() {
16+
return (int) (this.length * this.length * 3.14);
17+
}
18+
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.baeldung.javafeatures.shapes;
2+
3+
public abstract class Shape {
4+
private int sides;
5+
private int length;
6+
Shape(int sides, int length) {
7+
this.sides = sides;
8+
this.length = length;
9+
}
10+
11+
abstract int getArea();
12+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.javafeatures.shapes;
2+
3+
public class Square extends Shape {
4+
int sides;
5+
int length;
6+
7+
public Square(int sides, int length) {
8+
if (sides != 4 && length <= 0) {
9+
throw new IllegalArgumentException("Cannot form Square");
10+
}
11+
super(sides, length);
12+
}
13+
14+
@Override
15+
int getArea() {
16+
return 4 * length;
17+
}
18+
19+
public String whoAmI() {
20+
return "I am a square";
21+
}
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.baeldung.javafeatures;
2+
3+
import java.io.IOException;
4+
import java.util.List;
5+
6+
import org.junit.Assert;
7+
import org.junit.Test;
8+
9+
import com.baeldung.javafeatures.classfile.ClassFileDriver;
10+
11+
public class Java22ExamplesUnitTest {
12+
13+
@Test
14+
public void givenJava22_whenUsingLanguagePatterns_thenReturnResult() {
15+
UnnamedExpressions um = new UnnamedExpressions();
16+
Assert.assertEquals(0, um.unnamedExpressionExampleUsingException(100));
17+
Assert.assertEquals(123, um.unnamedExpressionsExampleUsingSwitch(123));
18+
Assert.assertTrue(um.unnamedExpressionForTryWithResources());
19+
Assert.assertNotNull(um.unnamedExpressionForLambda());
20+
}
21+
22+
@Test
23+
public void givenJava22_whenUsingClassFileAPI_thenReturnUpdatedClass() throws IOException {
24+
ClassFileDriver classFileDriver = new ClassFileDriver();
25+
Assert.assertNotNull(classFileDriver.updateClass());
26+
}
27+
28+
@Test
29+
public void givenJava22_whenUsingForeignAPI_thenReturnLengthUsingCFunction() throws Throwable {
30+
MemoryAPIExample mp = new MemoryAPIExample();
31+
Assert.assertEquals(11, mp.getLengthUsingNativeMethod("Hello world"));
32+
}
33+
34+
@Test
35+
public void givenJava22_whenUsingStreamGatherer_thenReturnCustomList() {
36+
Assert.assertNotNull(new StreamGatherersExample().gatherIntoWindows(List.of("India", "Poland", "UK", "Australia", "USA", "Netherlands")));
37+
}
38+
}

core-java-modules/pom.xml

+1
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,7 @@
228228
<module>java-spi</module>
229229
<module>java-websocket</module>
230230
<module>core-java-8-datetime-3</module>
231+
<!--<module>core-java-22</module>--> <!-- requires JDK 22 -->
231232
</modules>
232233

233234
<dependencies>

0 commit comments

Comments
 (0)