phax / jcodemodel

A heavily extended fork of the com.sun.codemodel (from 2013/09)
Other
93 stars 34 forks source link

synchronized block generation #25

Closed sviperll closed 9 years ago

sviperll commented 9 years ago

I've found no way to generate synchronized block like this:

void method1() {
    synchronized(lock) {
         // some synchronized data access here
    }
}
UnquietCode commented 9 years ago

As a workaround, you can use a direct statement. Note that if the block ends up empty then it probably won't print right and thus cause a compile error.

method.body().directStatement("synchronized(lock)");
JBlock synchronizedBlock = method.body().block();
sviperll commented 9 years ago

Actually, I've done it like this:

    public static JBlock addSynchronizedBlock(JBlock body, final IJExpression lock) {
        /*
         * HACK:
         *  jcodemodel currently provides no support for synchronized blocks.
         *  Implement synchronized block right here:
         */
        final JBlock synchronizedBlock = new JBlock(true, true) {
        };
        body.add(new IJStatement() {
            @Override
            public void state(JFormatter f) {
                f.print("synchronized (").generable(lock).print(") ").generable(synchronizedBlock).newline();
            }
        });
        return synchronizedBlock;
    }
phax commented 9 years ago

I will add a nicer method to do it. Stay tuned

sviperll commented 9 years ago

Besides

JBlock synchronizedBlock = method.body().block();

doesn't work. Created block is rendered without parenthesis and indentation no matter what.

phax commented 9 years ago

Now contained in the trunk. method.body.synchronizedBlock (expr). Implementation class is JSynchronizedBlock.