java - 你能“动态绑定”重载方法吗?
问题描述
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 参数调用构造函数,它只是不知道调用正确的构造函数,毕竟......
另外——因为我猜答案是“不”——允许这样的事情会有什么问题?
解决方案
我的意思是,应用程序在运行时知道它应该使用整数类型参数调用构造函数,它只是不知道调用正确的构造函数,毕竟......
不,它没有。
这种方法:
public <T> B bWith(T it){return new B(it);}
必须能够为任何参数工作:编译器必须选择一个构造函数以在该方法中调用。唯一符合该标准的构造函数就是那个Object
。
在运行时让它做不同的唯一方法是显式转换(你也可以删除类型参数,它是多余的):
public B bWith(Object it){
if (it == null || it instanceof Integer) {
return new B((Integer) it);
}
return new B(it);
}
编辑:添加了it == null
检查,因为它new B(null)
实际上会调用Integer
构造函数,因为它是两者中更具体的。
推荐阅读
- python - 构造将在类方法中调用的私有方法的正确方法是什么?
- pddl - 多级类型继承,x继承自y继承自z
- sql - MSAccess 中的 VLOOKUP
- python - 无法在 Raspberry Pi 中进行 apt-get 更新工作
- python - Python:如何将整个数组转换为 int
- java - Throws and Throw - 这个解释正确吗?
- java - 如何在孩子中获取 dataSnapshot.getChildrenCount()
- c++ - 如何让 WaitForSingleObject 在作为类成员函数从 main 调用的线程内接收信号?
- python-2.7 - 如何在python中截取屏幕截图?
- callback - 如何在 Dash/Plotly 的聚集条形图中通过回调保持选定数据的持久性