java运算符`+`和`StringBuilder.append`

时间:2014-09-30 05:31:05

标签: java decompiler

据说当我使用+运算符来连接String时,它会转换为StringBuilder.append但是当我运行Java Decompiler GUI并打开MainClass.class时,

public class MainClass
{
  public static void main(String[] paramArrayOfString)
  {
    String str1 = "abc";
    String str2 = "def";

    String str3 = str1 + str2;
  }
}

当原件

public class MainClass {

    public static void main(String[] args) {

        String val1 = "abc";
        String val2 = "def";

        String res = val1 + val2;

    }
}

有什么问题? 我使用javac MainClass.java

编译了它

1 个答案:

答案 0 :(得分:4)

大多数反编译器会自动将编译器生成的StringBuilder序列转换回与+的字符串连接。

为数不多的是Krakatau之一。如果您使用Krakatau反编译该类,您将获得类似

的内容
public class MainClass {
    public MainClass()
    {
        super();
    }

    public static void main(String[] a)
    {
        new StringBuilder().append("abc").append("def").toString();
    }
}

正如您所看到的,StringBuilder代码就在那里。你也可以看一下反汇编。

.version 51 0
.source MainClass.java
.class super public MainClass
.super java/lang/Object


.method public <init> : ()V
    ; method code size: 5 bytes
    .limit stack 1
    .limit locals 1
    aload_0
    invokespecial java/lang/Object <init> ()V
    return
.end method

.method static public main : ([Ljava/lang/String;)V
    ; method code size: 26 bytes
    .limit stack 2
    .limit locals 4
    ldc 'abc'
    astore_1
    ldc 'def'
    astore_2
    new java/lang/StringBuilder
    dup
    invokespecial java/lang/StringBuilder <init> ()V
    aload_1
    invokevirtual java/lang/StringBuilder append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    aload_2
    invokevirtual java/lang/StringBuilder append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    invokevirtual java/lang/StringBuilder toString ()Ljava/lang/String;
    astore_3
    return
.end method