1

The following code is used in Spring - Hibernate Full Java Based Configuration in many places (like here):

Properties hibernateProperties() {
        return new Properties() {
            {
                setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
                setProperty("hibernate.show_sql", "true");
                setProperty("hibernate.format_sql", "true");
                setProperty("use_sql_comments", "true");
                setProperty("hibernate.hbm2ddl.auto", "none");
            }
        };
    }

This is a method in a class. I think that the return object is an anonymous class object (Please tell me if I'm wrong). What is with the curly brackets enclosing the setProperty statements? Is that an array? If so there should not be any semi-colons in there?

I haven't been able to find any place where this syntax is explained. Please give some link where this explained in detail.

2 Answers2

0

This is a method that returns an object of type Properties. The method creates an anonymous class which defines an instance initializer block that sets some properties in the returned object:

return new Properties() {
    // this is an instance initializer block which pre-sets some properties
    {
         setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
         setProperty("hibernate.show_sql", "true");
         setProperty("hibernate.format_sql", "true");
         setProperty("use_sql_comments", "true");
         setProperty("hibernate.hbm2ddl.auto", "none");
     }
};

It creates a Properties object with predefined properties.

M A
  • 71,713
  • 13
  • 134
  • 174
0

Classes can have initialization blocks in them (static and non-static). In case of non-static blocks their code will be moved at start of each constructor of your class (actually almost at start because it will be placed right after explicit or implicit super() call).

So class like

class Foo{

    void method(){
        System.out.println("method()");
    }

    Foo(){
        System.out.println("constructor of Foo");
    }

    {
        System.out.println("initialization block");
        method();
    }

    public static void main(String[] args) {
        Foo f = new Foo();
    }

}

is same as

class Foo {

    void method() {
        System.out.println("method()");
    }

    Foo() {
        super();
        //initialization block is moved here
        {
            System.out.println("initialization block");
            method();
        }
        System.out.println("constructor of Foo");
    }


    public static void main(String[] args) {
        Foo f = new Foo();
    }

}

So inside this initialization block you are able to invoke any method of Foo class, just like you are able to invoke them inside constructor.

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269