views:

56

answers:

4

Hello,

I want to make sure all getters of the classes in a certain package follow a given template.

For example, all getters must be of the form:

XXX getYYY(){
    classLock.lock(); 
    return YYY;
    finally{
        classLock.unlock(); 
    }
}

Basically, I want that my project will not compile/run unless all getters are of that form.

What is the best way to do that? I would prefer a solution that can be used as an Eclipse plugin.

Thanks, Yoav

+4  A: 

There is no way to force the compiler to do that check. You might want to look into static code analysis tools such as PMD or CheckStyle and define your own rule for this.

Then call that tool during your build cycle and make it a fatal error if that check fails on any class.

But I'm not sure that that kind of getter would any level of thread safety to your code. You would still be able to read inconsistent values when you call two getters in a row.

Joachim Sauer
A: 

You could write an Eclipse plugin for this purpose.

There is an API for Builders (compiler-like plugins) and you can access the AST (Abstract Syntax Tree) of the Eclipse Java compiler to perform your checks.

It should not be a big deal if you are into eclipse plugins.

Article about AST
Article about Builders

Hardcoded
+5  A: 

Why not use AspectJ (or some other aspect-oriented framework) to automatically wrap your getters during the compilation phase ? You can simply specify the type of methods you want to wrap (in a particular set of classes, say) and specify the code to provide pre/post execution.

Brian Agnew
Would I still be able to properly debug my code after the build-time injection?
Yoav Schwartz
Yes. It'll be using byte-code weaving, so line numbers etc. will be maintained.
Brian Agnew
A: 

+1 For Brians suggestion, OR use something similar on the runtime, like Spring AOP. With runtime framework you have the advantage that you don't need a separate compiler and you can remove the wrapping from all methods by just removing one line from a context file.

fish