java - 使用类构造函数操作 Java 对象引用

标签 java

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

How do you get the following java code to print false by only editing code within the MyClass constructor?

public class MyClass{        
    public MyClass(){
    }

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

You are NOT allowed to override the equals method, or change any of the code within the main method. The code must run without the program crashing.

根据我的研究,实例化类时不能将 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); 
    }
});

或者 AJ Neufeld 的更简单的建议:

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

关于java - 使用类构造函数操作 Java 对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36365618/

相关文章:

java - 安装 Mac OS X Yosemite (Mac OS 10.10) 后 Eclipse 无法启动

java - 从字符串中删除特殊的 html 标签

java - 在tomcat中使用axis2的Web服务

java - 如何将哈希表添加到 NameValuePair 中?

java - 如何使用 <span> 或任何其他 HTML 标签包装部分文本而不转义新的 HTML 结构?

java - Spring @Value 无法识别 Interger 属性值

java - 将 org.bytedeco.javacpp.Mat 转换为 Java int/float 数组

java - 如何访问 map 中嵌套 map 中的项目 (Java)

Java MQQueueConnection 获取客户端和服务器版本

java - 在 Java 应用程序 WADL 中获取燃油价格的 Web 服务