Java syntax sugar

I came across this code block today. I don't know how it works I know how to do anonymous classes, but I'm used to seeing a method signature, not just a pair of braces Is the code between these braces placed in static blocks? Does it enter the constructor? Or something else?

conext.checking(new Expectations() {
    { // <- what does this pair of braces do?
        oneOf(alarm).getAttackAlarm(null);
    }
});

Solution

It is an instance initializer that invokes code through the context of the created object

This is equivalent to

Expectations exp = new Expectations();
exp.oneOf(alarm).getAttackAlarm(null);
conext.checking(exp)

Whoever writes may think that he does not declare a variable (not true), or that it is cleaner code (I disagree) is more efficient

The main purpose of these initializers is to instantiate mappings, namely:

Map map = new HashMap() {{
  put("key1","value1");   
  put("key2","value2"); 
}};

I think it's actually a little more readable

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>