gpt4 book ai didi

java - 你可以 "dynamically bind"重载方法吗?

转载 作者:行者123 更新时间:2023-11-30 06:40:40 25 4
gpt4 key购买 nike

<分区>

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类型的参数调用构造函数,它只是不知道调用构造函数,毕竟...

另外——因为我猜答案是“否”——允许这样的事情会有什么问题?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com