java为我们提供了javap命令来查看class字节码,下面以实例来进行说明。首先写一段单例懒加载的代码:

class Singleton{
    private volatile static Singleton instance = null;
 
    private Singleton() {}
 
    public static Singleton getInstance() {
        if(instance==null) {
            synchronized (Singleton.class) {
                if(instance==null)
                    instance = new Singleton();
            }
        }
        return instance;
    }
}

对上面代码进行编译,操作,这里采用idea的maven环境进行编译,编译之后,class文件位于target目录下。

java javap查看class字节码插图

然后通过idea提供的Terminal工具,进入该目录:

ershixiongdeMacBook-Pro:java-stream zzs$ cd target/classes/com/secbro2/singleton/
ershixiongdeMacBook-Pro:singleton zzs$ ls
Singleton.class
ershixiongdeMacBook-Pro:singleton zzs$ 

然后执行以下命令,并获得字节码内容:

javap -c Singleton.class 
Compiled from "Singleton.java"
public class com.secbro2.singleton.Singleton {
  public static com.secbro2.singleton.Singleton getInstance();
    Code:
       0: getstatic     #2                  // Field instance:Lcom/secbro2/singleton/Singleton;
       3: ifnonnull     37
       6: ldc           #3                  // class com/secbro2/singleton/Singleton
       8: dup
       9: astore_0
      10: monitorenter
      11: getstatic     #2                  // Field instance:Lcom/secbro2/singleton/Singleton;
      14: ifnonnull     27
      17: new           #3                  // class com/secbro2/singleton/Singleton
      20: dup
      21: invokespecial #4                  // Method "<init>":()V
      24: putstatic     #2                  // Field instance:Lcom/secbro2/singleton/Singleton;
      27: aload_0
      28: monitorexit
      29: goto          37
      32: astore_1
      33: aload_0
      34: monitorexit
      35: aload_1
      36: athrow
      37: getstatic     #2                  // Field instance:Lcom/secbro2/singleton/Singleton;
      40: areturn
    Exception table:
       from    to  target type
          11    29    32   any
          32    35    32   any

  static {};
    Code:
       0: aconst_null
       1: putstatic     #2                  // Field instance:Lcom/secbro2/singleton/Singleton;
       4: return
}

查看字节码对于java内部执行的逻辑可以有很好的理解,特别是对于线程并发相关方面的有非常大的帮助。



java javap查看class字节码插图1

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:https://choupangxia.com/2019/11/08/java-javap-class/