我收到了一个普通的问题,是由于某人无意中给一个类的一个变量取了一个与另一个类相同名称的名字,而这两个类都有一个同名方法,其中一个是静态的。
考虑以下情况:
public class A {
public static String dothis(String string){
return "Class";
}
public static String dothis(String string, String string2){
return "Class Method 2";
}
}
并且这个
public class B {
public String dothis(String string){
return "Object";
}
}
一旦实例化对象,以下代码是否总是调用对象而不是静态方法?
System.out.println(A.dothis("..."));//outputs Class
B A = new B();
System.out.println(A.dothis("..."));//outputs Object
注意,实例化之后似乎不可能调用类A中的任何静态方法,即:
B A = new B();
System.out.println(A.dothis("..."));
System.out.println(A.dothis("...","..."));//Won't compile
以上代码无法编译,报告错误的树类型。
编辑:添加具体的异常信息:-
java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
at testbed.....
这是什么意思呢?编译器实际上在决定调用哪个方法,因此不同的javac版本可能会有不同的行为。
这里到底发生了什么,如果这是有保证的,是否可以以某种方式用于混淆,或者反编译会移除名称冲突吗?