使用类构造函数处理Java对象引用

这是一个我无法完成的考试问题。

如何只通过编辑MyClass构造函数中的代码来获取以下java代码来打印false

public class MyClass{ public MyClass(){ } public static void main(String[] args) { MyClass m = new MyClass(); System.out.println(m.equals(m)); } } 

不允许覆盖equals方法,或更改main方法中的任何代码。 代码必须在程序崩溃的情况下运行。

根据我的研究,在实例化类时,不能将Java对象引用设置为null。 所以我正式难过。

那太难了!

 public MyClass() { System.setOut(new PrintStream(new FilterOutputStream(System.out) { @Override public void write(byte[] b, int off, int len) throws IOException { if(new String(b).contains("true")) { byte[] text = "false".getBytes(); super.write(text, 0, text.length); } else { super.write(b, off, len); } } }, true)); } 

或Paul Boddington的简化版:

 PrintStream p = System.out; System.setOut(new PrintStream(p) { @Override public void println(boolean b) { p.println(false); } }); 

我想,沿着这些方向的东西:

 public MyClass() { System.out.println(false); System.exit(0); } 

编辑:我发现了一个与Java Puzzlers非常类似的谜题,除了在那个问题中唯一的限制是你不能覆盖 equals,这基本上使得解决方案重载它而只是返回false 。 顺便提一下,我的上述解决方案也作为该难题的替代答案。

另一个解决方案是

 public MyClass() { new PrintStream(new ByteArrayOutputStream()).println(true); try { Field f = String.class.getDeclaredField("value"); f.setAccessible(true); f.set("true", f.get("false")); } catch (Exception e) { } } 

第一行是必需的,因为在修改后备数组之前,必须在PrintStream类中遇到字符串文字"true" 。 看到这个问题 。

这是我的解决方案

 public class MyClass { public MyClass() { System.out.println("false"); // New class class NewPrintStream extends PrintStream { public NewPrintStream(OutputStream out) { super(out); } @Override public void println(boolean b) { // Do nothing } } NewPrintStream nps = new NewPrintStream(System.out); System.setOut(nps); } public static void main(String[] args) { MyClass m = new MyClass(); System.out.println(m.equals(m)); } } 

基本上,这是@fikes解决方案的变体。