我被认为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
方法?
答案 0 :(得分:4)
表达式,如
action == 0 ? "" : action
可以有一个返回类型。编译器将此理解为返回Object
实例的表达式。这在运行时可以是String
或Integer
。
在您的情况下,将调用append(Object)
。然后StringBuilder实现将在参数上调用toString()
,这将为您提供预期的结果(""
或转换为String的整数值)。
答案 1 :(得分:0)
StringBuilder有许多称为append的重载方法。所以对于大多数类型有不同的附加。任何其他类型都是Object。
StringBuilder append(boolean b)
Appends the string representation of the boolean argument to the sequence.
StringBuilder append(char c)
Appends the string representation of the char argument to this sequence.
StringBuilder append(char[] str)
Appends the string representation of the char array argument to this sequence.
StringBuilder append(char[] str, int offset, int len)
Appends the string representation of a subarray of the char array argument to this sequence.
StringBuilder append(CharSequence s)
Appends the specified character sequence to this Appendable.
StringBuilder append(CharSequence s, int start, int end)
Appends a subsequence of the specified CharSequence to this sequence.
StringBuilder append(double d)
Appends the string representation of the double argument to this sequence.
StringBuilder append(float f)
Appends the string representation of the float argument to this sequence.
StringBuilder append(int i)
Appends the string representation of the int argument to this sequence.
StringBuilder append(long lng)
Appends the string representation of the long argument to this sequence.
StringBuilder append(Object obj)
Appends the string representation of the Object argument.
StringBuilder append(String str)
Appends the specified string to this character sequence.
StringBuilder append(StringBuffer sb)