赞
踩
在Java中是不支持重载运算符的,String的+
是java中唯一的一个重载运算符,那么java使如何实现这个加号的呢?我们先看一段代码:
public static void main(String[] args) {
String s1 = "yves";
String s2 = s1 + "he";
}
反编译结果如下:
public static void main(String[] args) {
String s1 = "yves";
String s2 = (new StringBuilder(String.valueOf(s1))).append("he").toString();
}
javap结果如下
javap -c StringPlus.class
Compiled from "StringPlus.java" public class com.yveshe.StringPlus { public com.yveshe.StringPlus(); Code: 0: aload_0 1: invokespecial #8 // Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: ldc #16 // String yves 2: astore_1 3: new #18 // class java/lang/StringBuilder 6: dup 7: aload_1 8: invokestatic #20 // Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String; 11: invokespecial #26 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V 14: ldc #29 // String he 16: invokevirtual #31 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 19: invokevirtual #35 // Method java/lang/StringBuilder.toString:()Ljava/lang/String; 22: astore_2 23: return }
结论:
看了反编译之后的代码我们发现,其实String对+
的支持其实就是使用了StringBuilder以及他的append、toString两个方法。
String s1 = "yves" + "he";
System.out.println(s1 == "yveshe");
输出结果为true
反编译代码为
String s1 = "yveshe";
System.out.println(s1 == "yveshe");
这里是由于String s1 = "yves" + "he";
在编译期常量折叠成String s1 = "yveshe";
所以输出结果为true.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。