2013-06-02 69 views
4

作爲我學校項目的一部分,我需要深入研究java字節碼。我開始編寫簡單的程序並使用javap實用程序來查看生成的字節碼,並且我有一個關於*ipush指令的問題。java字節碼 - 無ipush指令

當我認爲這個代碼的字節代碼:

public class Main{ 
    public static void main(String []args){ 
    int a; 
    a=5; 
    a=a+32765; 
    } 
} 

我正在

public class Main 
    SourceFile: "Main.java" 
    minor version: 0 
    major version: 51 
    flags: ACC_PUBLIC, ACC_SUPER 
Constant pool: 
    #1 = Methodref   #3.#12   // java/lang/Object."<init>":()V 
    #2 = Class    #13   // Main 
    #3 = Class    #14   // java/lang/Object 
    #4 = Utf8    <init> 
    #5 = Utf8    ()V 
    #6 = Utf8    Code 
    #7 = Utf8    LineNumberTable 
    #8 = Utf8    main 
    #9 = Utf8    ([Ljava/lang/String;)V 
    #10 = Utf8    SourceFile 
    #11 = Utf8    Main.java 
    #12 = NameAndType  #4:#5   // "<init>":()V 
    #13 = Utf8    Main 
    #14 = Utf8    java/lang/Object 
{ 
    public Main(); 
flags: ACC_PUBLIC 
Code: 
    stack=1, locals=1, args_size=1 
    0: aload_0  
    1: invokespecial #1     // Method java/lang/Object."<init>":()V 
    4: return   
    LineNumberTable: 
    line 1: 0 

    public static void main(java.lang.String[]); 
flags: ACC_PUBLIC, ACC_STATIC 
Code: 
    stack=2, locals=2, args_size=1 
    0: iconst_5  
    1: istore_1  
    2: iload_1  
    3: sipush  32765 
    6: iadd   
    7: istore_1  
    8: return   
    LineNumberTable: 
    line 4: 0 
    line 5: 2 
    line 6: 8 
} 

並且當我換32765爲32769,其並不在短的範圍內我正在

public class Main 
    SourceFile: "Main.java" 
    minor version: 0 
    major version: 51 
    flags: ACC_PUBLIC, ACC_SUPER 
Constant pool: 
    #1 = Methodref   #4.#13   // java/lang/Object."<init>":()V 
    #2 = Integer   32769 
    #3 = Class    #14   // Main 
    #4 = Class    #15   // java/lang/Object 
    #5 = Utf8    <init> 
    #6 = Utf8    ()V 
    #7 = Utf8    Code 
    #8 = Utf8    LineNumberTable 
    #9 = Utf8    main 
    #10 = Utf8    ([Ljava/lang/String;)V 
    #11 = Utf8    SourceFile 
    #12 = Utf8    Main.java 
    #13 = NameAndType  #5:#6   // "<init>":()V 
    #14 = Utf8    Main 
    #15 = Utf8    java/lang/Object 
{ 
    public Main(); 
flags: ACC_PUBLIC 
Code: 
    stack=1, locals=1, args_size=1 
    0: aload_0  
    1: invokespecial #1     // Method java/lang/Object."<init>":()V 
    4: return   
    LineNumberTable: 
    line 1: 0 

    public static void main(java.lang.String[]); 
flags: ACC_PUBLIC, ACC_STATIC 
Code: 
    stack=2, locals=2, args_size=1 
    0: iconst_5  
    1: istore_1  
    2: iload_1  
    3: ldc   #2     // int 32769 
    5: iadd   
    6: istore_1  
    7: return   
    LineNumberTable: 
    line 4: 0 
    line 5: 2 
    line 6: 7 
} 

所以現在號碼被存儲在常量池中。我知道有沒有指令ipush,我可以用來推動整數常量堆棧,但我想知道爲什麼沒有這樣的指令?

+1

這是由於字節碼指令大小的一般限制。整數不適合一個指令。 –

+1

@Marko這是不正確的。有任意的長指令(tableswitch,lookupswitch)。真正的原因是,如果你必須指定整個int,那麼不妨將它放在常量池中。 – Antimony

回答

3

基於簡單的CISC設計,他們試圖使每條指令儘可能短(以字節爲單位)使用32位或64位常量的指令更容易/更短以引用常量表。