这是本书中的一个问题:https://www.cl.cam.ac.uk/teaching/0506/ConcSys/cs_a-2005.pdf第28页
你能编写一个额外的Java类来创建一个对象,当传递给测试方法时会导致它打印"Here!"吗?正如我在代码中所说,编辑A类本身,或使用反射,序列化或本机方法等库功能被视为作弊!如果没有人能在一周左右发现它,我会在讲座中提供一些提示.博士生都没有得到它.
public class A {
// Private constructor tries to prevent A
// from being instantiated outside this
// class definition
//
// Using reflection is cheating :-)
private A() {
}
// ’test’ method checks whether the caller has
// been able to create an instance of the ’A’
// class. Can this be done even though the
// constructor is private?
public static void test(Object o) {
if (o instanceof A) {
System.out.println("Here!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这个问题很不清楚.我可以想到许多不同的'hack-ish'解决方案,但不确定它们是否会被视为'作弊'或者不是:)
我找不到官方的答案,所以问你一个好的答案.
Ric*_*cky -3
Java可以支持unicode类名:)
\n\n“if (o instanceof A)”中的 A 可能与“public class A”中的 A 不同
\n\n例如,下面的代码将打印“Here!” 而不是“坏”。
\n\nA.java
\n\npublic class A {\n // Private constructor tries to prevent A\n // from being instantiated outside this\n // class definition\n //\n // Using reflection is cheating :-)\n private A() {\n // A: U+0041\n }\n\n // \xe2\x80\x99test\xe2\x80\x99 method checks whether the caller has\n // been able to create an instance of the \xe2\x80\x99A\xe2\x80\x99\n // class. Can this be done even though the\n // constructor is private?\n public static void test(Object o) {\n if (o instanceof \xd0\x90) {\n System.out.println("Here!");\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n\xd0\x90.java
\n\npublic class \xd0\x90 {\n // A: U+0410, not A: U+0041\n}\nRun Code Online (Sandbox Code Playgroud)\n\n主程序.java
\n\npublic class Main {\n public static void main(String[] args) {\n A.test(new \xd0\x90());\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n