鍍金池/ 問(wèn)答/Java  網(wǎng)絡(luò)安全/ java中,這是什么寫(xiě)法?

java中,這是什么寫(xiě)法?

HttpHeaders createHeaders(String username, String password){
      return new HttpHeaders() {{
          String auth = username + ":" + password;
          byte[] encodedAuth = Base64.encodeBase64( 
             auth.getBytes(Charset.forName("US-ASCII")) );
          String authHeader = "Basic " + new String( encodedAuth );
          set( "Authorization", authHeader );
      }};
 }

從論壇上看到這段代碼,大致知道該方法的作用,但是 new HttpHeaders() 之后為啥這樣寫(xiě)?。靠戳?code>HttpHeaders的構(gòu)造函數(shù)有兩個(gè),一個(gè)無(wú)參,一個(gè)三參。不理解圖中這種寫(xiě)法,望各位告知,謝謝

======================================分割線======================================

首先謝謝各位的回答,我搜了下關(guān)于代碼塊,構(gòu)造代碼塊,靜態(tài)代碼塊的相關(guān)知識(shí)。寫(xiě)了個(gè)測(cè)試代碼,

public class Demo01 {
String name ;

public Demo01(String name){
    System.out.println("構(gòu)造函數(shù)");
    this.name = name;
}
{
    System.out.println("類(lèi)中的構(gòu)造代碼塊");
}
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public void show(){
    System.out.println(name);
}
public static void main(String[] args) {
    Demo01 demo = new Demo01("11"){{
            System.out.println("構(gòu)造代碼塊???");
            setName("22");
        }};
    demo.show();
}
}

執(zhí)行結(jié)果如下:

clipboard.png

問(wèn) :如果是構(gòu)造代碼塊,執(zhí)行時(shí)應(yīng)該是先于構(gòu)造函數(shù),但打印結(jié)果卻是最后執(zhí)行,所以到底是不是構(gòu)造代碼塊呢?如果不是,那這種寫(xiě)法就是普通代碼塊嗎?

回答
編輯回答
墨小羽

其實(shí)很簡(jiǎn)單,使用javac編譯之后得到兩個(gè)class(Demo01.class Demo01$1.class),我貼上來(lái)你看一下。

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

public class Demo01 {
    String name;

    public Demo01(String var1) {
        System.out.println("類(lèi)中的構(gòu)造代碼塊");
        System.out.println("構(gòu)造函數(shù)");
        this.name = var1;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String var1) {
        this.name = var1;
    }

    public void show() {
        System.out.println(this.name);
    }

    public static void main(String[] var0) {
        Demo01 var1 = new Demo01("11") {
            {
                System.out.println("構(gòu)造代碼塊???");
                this.setName("22");
            }
        };
        var1.show();
    }
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

final class Demo01$1 extends Demo01 {
    Demo01$1(String var1) {
        super(var1);
        System.out.println("構(gòu)造代碼塊???");
        this.setName("22");
    }
}
2017年12月25日 21:43
編輯回答
硬扛

樓上正解,是生成一個(gè)類(lèi)Demo01$1繼承Demo01,然后在Demo01$1的構(gòu)造器里面先調(diào)用父類(lèi)Demo01的構(gòu)造器, System.out.println("構(gòu)造代碼塊???");是子類(lèi)構(gòu)造器里面的一行代碼。。。。

2018年6月19日 02:30
編輯回答
生性

這種方法是匿名對(duì)象的方法,然后在構(gòu)造代碼塊執(zhí)行代碼,構(gòu)造代碼塊會(huì)比構(gòu)造方法先執(zhí)行。

2017年11月28日 12:59
編輯回答
莓森

里面是個(gè)構(gòu)造代碼塊,然后,回想一下,Java中代碼的執(zhí)行順序。

2017年6月14日 02:29