问题描述
我知道我们可以像这样设置 Charset
的 PrintStream
:
PrintStream printStream = new PrintStream( System.out,true,StandardCharsets.UTF_8.name() ); // "UTF-8".
有没有办法获取由Charset
对象(例如System.out
)使用的PrintStream
?像这样:
Charset charset = System.out.getCharset() ;
...但我在 PrintStream
上找不到任何这样的 getter。
这个问题是在解决 this Question 中的一个谜时提出的。
解决方法
你应该像这样使用反射 API。
PrintStream ps = new PrintStream(System.out,true,StandardCharsets.UTF_16);
Field f = ps.getClass().getDeclaredField("charOut");
f.setAccessible(true);
OutputStreamWriter charOut = (OutputStreamWriter) f.get(ps);
System.out.println(charOut.getEncoding());
输出:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by stackoverflow.AAA field java.io.PrintStream.charOut
WARNING: Please consider reporting this to the maintainers of stackoverflow.AAA
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
UTF-16
您需要注意最后一条警告信息。
我在 Eclipse 调试器中找到了字段 charOut
。