编译时的方法选择。如果参数可以有多种类型怎么办?
我被引导相信java编译器在编译时完成了方法选择的所有工作(或者我错了?)。也就是说,它将通过检查类层次结构和方法签名来准确决定在编译时在哪个类中使用哪个方法。在运行时所需要做的就是选择要调用其方法的对象,而这只能在继承链上工作。
如果是这样的话,这是如何运作的?
int action = getAction ();
StringBuilder s = new StringBuilder()
.append("Hello ") // Fine
.append(10) // Fine too
.append(action == 0 ? "" : action); // How does it do this?
这里,参数的类型可以是String
或int
。它如何在编译时决定应该调用 StringBuilder 的哪个方法?
I am led to believe that the java compiler does all the work of method selection at compile time (or am I wrong?). That is, it will decide exactly which method to use in which class at compile time by examining the class hierarchy and method signatures. All that is then required at run time is to choose the object whose method is to be called and this can only work up the inheritance chain.
If that is the case, how does this work?
int action = getAction ();
StringBuilder s = new StringBuilder()
.append("Hello ") // Fine
.append(10) // Fine too
.append(action == 0 ? "" : action); // How does it do this?
Here, the type of the parameter can be either String
or int
. How can it decide at compile time which method of StringBuilder
should be invoked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
诸如此类的表达式
可以具有单一返回类型。编译器将其理解为返回
Object
实例的表达式。在运行时,它可以是String
或Integer
。在您的情况下,将调用
append(Object)
。然后,StringBuilder 实现将对参数调用toString()
,这将为您提供预期结果(""
或转换为字符串的整数值)。An expression such as
can have a single return type. The compiler understands this as an expression returning an
Object
instance. This, at runtime, can be eitherString
orInteger
.In your case,
append(Object)
will be called. The StringBuilder implementation will then calltoString()
on the parameter, which will give you the expected result (either""
or an integer value converted to String).StringBuilder 有许多称为append 的重载方法。因此,大多数类型都有不同的附加。任何其他类型都是对象。
StringBuilder has a many overloaded methods called append. So there is a different append for most type. Any other type is an Object.