这是indexloc提供的服务,不要输入任何密码
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions core-java-modules/core-java-22/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>

<artifactId>core-java-22</artifactId>


<properties>
<maven.compiler.source>22</maven.compiler.source>
<maven.compiler.target>22</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>22</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>22</source>
<target>22</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
void main() {
System.out.println("This is an implicitly declared class without any constructs");

int x = 165;
int y = 100;

System.out.println(y + x);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.baeldung.javafeatures;

public class MainApp {
public static void main(String[] args) {
System.out.println("Hello");
MultiFileExample mm = new MultiFileExample();
mm.ping(args[0]);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.baeldung.javafeatures;

import static java.lang.foreign.FunctionDescriptor.*;

import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;

public class MemoryAPIExample {
public long getLengthUsingNativeMethod(String string) throws Throwable {
SymbolLookup stdlib = Linker.nativeLinker().defaultLookup();
MethodHandle strlen =
Linker.nativeLinker()
.downcallHandle(
stdlib.find("strlen").orElseThrow(),
of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));

try (Arena offHeap = Arena.ofConfined()) {
MemorySegment str = offHeap.allocateFrom(string);

long len = (long) strlen.invoke(str);
System.out.println("Finding String length using strlen function: " + len);
return len;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.baeldung.javafeatures;

public class MultiFileExample {
public void ping(String s) {
System.out.println("Ping from Second File " + s);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.baeldung.javafeatures;

import java.util.Random;

public class ScopedValueExample {
public final static ScopedValue<User> LOGGED_IN_USER = ScopedValue.newInstance();

public void serve(Request request) {
User loggedInUser = authenticateUser(request);
ScopedValue.where(LOGGED_IN_USER, loggedInUser)
.run(() -> processRequest(request));
}

private User authenticateUser(Request request) {
return new User(new Random().nextInt(100), STR."User\{new Random().nextInt()}");
}

private void processRequest(Request request) {
System.out.println("Processing request :: " + ScopedValueExample.LOGGED_IN_USER.get()
.toString());
}
}

class User {
private int id;
private String userName;

public User(int id, String userName) {
this.id = id;
this.userName = userName;
}

public String toString() {
return STR."User :: \{this.id}";
}
}

class Request {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.baeldung.javafeatures;

import java.util.List;
import java.util.stream.Gatherers;

public class StreamGatherersExample {
public List<List<String>> gatherIntoWindows(List<String> countries) {
List<List<String>> windows = countries.stream()
.gather(Gatherers.windowSliding(3))
.toList();
return windows;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.baeldung.javafeatures;

import static java.lang.StringTemplate.STR;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

public class UnnamedExpressions {
private Logger LOGGER = Logger.getLogger(String.valueOf(UnnamedExpressions.class));

public int unnamedExpressionExampleUsingException(int someNumber) {
int divided = 0;
try {
divided = someNumber / 0;
} catch (ArithmeticException _) {
System.err.println("Division by zero");
}
return divided;
}

public Object unnamedExpressionsExampleUsingSwitch(Object obj) {
switch (obj) {
case Integer _ -> System.out.println("Is an integer");
case Float _ -> System.out.println("Is a float");
case String _ -> System.out.println("Is a String");
default -> System.out.println("Default");
}
;
return obj;
}

public boolean unnamedExpressionForTryWithResources() {
String url = "localhost";
String user = "user";
String pwd = "password";
try (Connection _ = DriverManager.getConnection(url, user, pwd)) {
LOGGER.info(STR."""
DB Connection successful
URL = \{url}
usr = \{user}
pwd = \{pwd}""");
} catch (SQLException e) {
LOGGER.warning("Exception");
}
return true;
}

public Map<String, List<String>> unnamedExpressionForLambda() {
Map<String, List<String>> map = new HashMap<>();
map.computeIfAbsent("v1", _ -> new ArrayList<>())
.add("0.1");
return map;
}

}

Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.baeldung.javafeatures.classfile;

import java.io.IOException;
import java.lang.classfile.ClassElement;
import java.lang.classfile.ClassFile;
import java.lang.classfile.ClassModel;
import java.lang.classfile.MethodModel;
import java.nio.file.Files;
import java.nio.file.Path;

public class ClassFileDriver {
public Path updateClass() throws IOException {
final String PREFIX = "test_";
final Path PATH = Path.of("src/main/java/com/baeldung/javafeatures/classfile/ClassFileExample.class");
ClassFile cf = ClassFile.of();
ClassModel classModel = cf.parse(PATH);
byte[] newBytes = cf.build(classModel.thisClass().asSymbol(), classBuilder -> {
for (ClassElement ce : classModel) {
if (!(ce instanceof MethodModel mm && mm.methodName()
.stringValue()
.startsWith(PREFIX))) {
classBuilder.with(ce);
}
}
});
return Files.write(PATH, newBytes);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.baeldung.javafeatures.classfile;

public class ClassFileExample {
public void doSomething() {
System.out.println("Do something here");
}

public void doSomething2() {
System.out.println("Do something here as well");
}

public void test_something() {
System.out.println("Test method");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.baeldung.javafeatures.shapes;

public class Circle extends Shape {
int sides;
int length;

Circle(int sides, int length) {
if (sides != 0 && length > 0) {
throw new IllegalArgumentException("Cannot form circle");
}
super(sides, length);
}

@Override
int getArea() {
return (int) (this.length * this.length * 3.14);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.baeldung.javafeatures.shapes;

public abstract class Shape {
private int sides;
private int length;
Shape(int sides, int length) {
this.sides = sides;
this.length = length;
}

abstract int getArea();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.baeldung.javafeatures.shapes;

public class Square extends Shape {
int sides;
int length;

public Square(int sides, int length) {
if (sides != 4 && length <= 0) {
throw new IllegalArgumentException("Cannot form Square");
}
super(sides, length);
}

@Override
int getArea() {
return 4 * length;
}

public String whoAmI() {
return "I am a square";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.baeldung.javafeatures;

import java.io.IOException;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;

import com.baeldung.javafeatures.classfile.ClassFileDriver;

public class Java22ExamplesUnitTest {

@Test
public void givenJava22_whenUsingLanguagePatterns_thenReturnResult() {
UnnamedExpressions um = new UnnamedExpressions();
Assert.assertEquals(0, um.unnamedExpressionExampleUsingException(100));
Assert.assertEquals(123, um.unnamedExpressionsExampleUsingSwitch(123));
Assert.assertTrue(um.unnamedExpressionForTryWithResources());
Assert.assertNotNull(um.unnamedExpressionForLambda());
}

@Test
public void givenJava22_whenUsingClassFileAPI_thenReturnUpdatedClass() throws IOException {
ClassFileDriver classFileDriver = new ClassFileDriver();
Assert.assertNotNull(classFileDriver.updateClass());
}

@Test
public void givenJava22_whenUsingForeignAPI_thenReturnLengthUsingCFunction() throws Throwable {
MemoryAPIExample mp = new MemoryAPIExample();
Assert.assertEquals(11, mp.getLengthUsingNativeMethod("Hello world"));
}

@Test
public void givenJava22_whenUsingStreamGatherer_thenReturnCustomList() {
Assert.assertNotNull(new StreamGatherersExample().gatherIntoWindows(List.of("India", "Poland", "UK", "Australia", "USA", "Netherlands")));
}
}
1 change: 1 addition & 0 deletions core-java-modules/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@
<module>java-spi</module>
<module>java-websocket</module>
<module>core-java-8-datetime-3</module>
<!--<module>core-java-22</module>--> <!-- requires JDK 22 -->
</modules>

<dependencies>
Expand Down