Java陷阱和缺陷

String.valueOf


example.java
1
2
3
4
String.valueOf(null);

->
java.lang.NullPointerException

why does it cause excepation? Java call the wrong method because type match!

String.java
1
2
3
4
5
6
7
public static String valueOf(char data[]) {
return new String(data);
}
...
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length); //=> cause exception.
}

how to correct?

1
2
3
String.valueOf((Object)null)
->
null

Varargs bug


Changes in Most Specific Varargs Method Selection
Description: The overload resolution algorithm in the javac compiler has been fixed in how it selects the most specific varargs method when more than one method is applicable to a given call-site (see the JLS, Java SE 7 Edition, section 15.12.2.5). Because of a bug, both JDK 5.0 and JDK 6 compilers reject the following legal code:

1
2
3
4
5
6
7
8
class Test {
void foo(int... i) {}
void foo(double... d) {}

void test() {
foo(1,2,3);
}
}

In the above example, both methods are applicable (because you can pass an int where a double is expected). Since both methods are applicable, the compiler must select the so-called most-specific method, that is, the best candidate among the two. This is done by looking at the signatures of both methods; in this case, since one method (foo(double…)) is accepting an argument that is more general than the other (foo(int…)), the answer is straightforward: the most specific method is foo(int…).
While the javac compiler accepts more code than it did prior to JDK 7, this fix also results in a slight source incompatibility in the following case:

1
2
3
4
5
6
7
8
class Test {
void foo(int... i) {}
void foo(Object... o) {}

void test() {
foo(1,2,3);
}
}

This code compiles in JDK 6 (the most specific method is foo(int…)). This code does not compile under JDK 7. As per 15.12.2.5, it is not possible to choose between foo(int…) and foo(Object…) as neither int is a subtype of Object, nor Object is a subtype of int. This program should be disallowed (in fact, it should never have been allowed in the first place).