开发者

Enforcing a coding template in the getters of a class in Java

开发者 https://www.devze.com 2022-12-26 06:32 出处:网络
I want to make sure all getters of th开发者_JAVA百科e classes in a certain package follow a given template.

I want to make sure all getters of th开发者_JAVA百科e 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.


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.


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 provide 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.


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


+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.

0

精彩评论

暂无评论...
验证码 换一张
取 消