public class ConstructorOverloading {
static class A{
final String msg;
public A(Object o){
this.msg = "via object";
}
public A(Integer i){
this.msg = "via integer";
}
}
public A aWith(Object o){return new A(o);}
public A aWith(Integer i){return new A(i); }
static class B{
final String msg;
public B(Object o){
this.msg = "via object";
}
public B(Integer i){
this.msg = "via integer";
}
}
public <T> B bWith(T it){return new B(it);}
public void test(){
A aO = aWith(new Object());
A aI = aWith(Integer.valueOf(14));
B bO = bWith(new Object());
B bI = bWith(Integer.valueOf(14));
System.out.println(format("a0 -> %s", aO.msg));
System.out.println(format("aI -> %s", aI.msg));
System.out.println(format("b0 -> %s", bO.msg));
System.out.println(format("bI -> %s", bI.msg));
}
}
给我们
a0 -> via object
aI -> via integer
b0 -> via object
bI -> via object
我想那是由于类型擦除。
我可以对此做任何事情而不必插入显式类型检查或重载bWith
吗?
我的意思是,应用程序在运行时知道它应该使用Integer
-type 参数调用构造函数,它只是不知道调用正确的构造函数,毕竟......
另外——因为我猜答案是“不”——允许这样的事情会有什么问题?