I was tracking down a bug today, and I noticed something strange within one of our classes. I cut out as much code as possible to post here:
class A {
static int obtainNumber() { return 42; }
static int obtainNumber() { return 3; }
static int obtainNumber() { return -1; }
static {
System.out.println(obtainNumber());
}
}
This class has 3 methods with the exact same name and signature. At first I thought this was invalid code, but then eclipse would have highlighted the code in red. It does work:
javac A.java && java A
42
Exception in thread "main" java.lang.NoSuchMethodError: main
So I figured maybe Java will just use the first one it sees. I reordered to test:
class A {
static int obtainNumber() { return 3; }
static int obtainNumber() { return -1; }
static int obtainNumber() { return 42; }
static {
System.out.println(obtainNumber());
}
}
Nope, same result:
javac A.java && java A
42
Exception in thread "main" java.lang.NoSuchMethodError: main
I thought perhaps it uses the one with 42 because its the biggest. To test this, I took the original and changed the return values:
class A {
static int obtainNumber() { return 0; }
static int obtainNumber() { return 1; }
static int obtainNumber() { return 2; }
static {
System.out.println(obtainNumber());
}
}
It still knows to use the first one:
javac A.java && java A
0
Exception in thread "main" java.lang.NoSuchMethodError: main
And if I reorder them again:
class A {
static int obtainNumber() { return 1; }
static int obtainNumber() { return 0; }
static int obtainNumber() { return 2; }
static {
System.out.println(obtainNumber());
}
}
Same result:
javac A.java && java A
0
Exception in thread "main" java.lang.NoSuchMethodError: main
I thought Java was a text based language, which I'd expect makes this sort of thing impossible. How is Java tracking which method is which?
解决方案
Hidden characters. The source code is equivalent to
static int obtainNumber() { return 42; }
static int obtain\ufeffNumber() { return 3; }
static int obtain\ufeff\ufeffNumber() { return -1; }
To avoid this kind of problems, my source files are strictly US-ASCII. I want to be certain that the characters I see are exactly the characters compiler sees.