Skip to content

Commit

Permalink
fix #27 on newer java versions where reflection is restricted
Browse files Browse the repository at this point in the history
  • Loading branch information
wagyourtail committed Feb 3, 2025
1 parent 704f8ea commit 0e55409
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,21 +1,37 @@
package xyz.wagyourtail.jvmdg.j18.stub.java_base;

import xyz.wagyourtail.jvmdg.util.Utils;
import xyz.wagyourtail.jvmdg.version.Stub;

import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.nio.charset.Charset;

public class J_I_PrintStream {
private static final MethodHandles.Lookup IMPL_LOOKUP = Utils.getImplLookup();
private static final MethodHandle getCharOut;

static {
try {
getCharOut = IMPL_LOOKUP.findGetter(PrintStream.class, "charOut", OutputStreamWriter.class);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}

@Stub
public static Charset charset(PrintStream printStream) throws NoSuchFieldException, IllegalAccessException {
Field charOut = PrintStream.class.getDeclaredField("charOut");
charOut.setAccessible(true);
OutputStreamWriter writer = (OutputStreamWriter) charOut.get(printStream);
String encoding = writer.getEncoding();
return Charset.forName(encoding);
public static Charset charset(PrintStream printStream) {
try {
OutputStreamWriter writer = (OutputStreamWriter) getCharOut.invokeExact(printStream);
String encoding = writer.getEncoding();
return Charset.forName(encoding);
} catch (Throwable e) {
Utils.sneakyThrow(e);
}
return null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class TestPrintWriter {


public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out, false, StandardCharsets.UTF_8);
PrintWriter out = new PrintWriter(System.out, false, System.out.charset());
out.println("Hello World!");

var temp = Files.createTempFile("temp", "txt");
Expand Down

0 comments on commit 0e55409

Please sign in to comment.