开发者

Is there a way to use static code analysis to determine if all fields of a certain type have an annotation?

开发者 https://www.devze.com 2023-03-10 09:38 出处:网络
I have some POJOs that are used to shuffle data around in my application and its webservices. We have just introduced an annotation to help us verify that String fields in those POJOs are of a certain

I have some POJOs that are used to shuffle data around in my application and its webservices. We have just introduced an annotation to help us verify that String fields in those POJOs are of a certain length. This lets us validate the POJOs instead of waiting for the database layer to puke out an exception when it persists.

I would now like to do an analysis on those objects that will tell me what fields are Strings that do not have this new annotation. I want to do this so that I can get a list of fields that do not have this annotation so that it can be compared to its corresponding DB field and have the annotation added with the right length as its parameter.

No we cannot get a better correlation between our POJOs and our database objects.

No our database objects don't have this validation available. We really want this validation to happen on the POJOs as it is simpler to validate and report on invalid data at runtime.

Is there some static analysis tool that would hel开发者_JS百科p me with this task?


Sure.

Parse the Java code. Walk the AST. Find the fields of interest (may require that you also do name and type resolution ("symbol tables") so you can tell your fields from arbitary other fields) in the ASTs for your classes, and inspect the AST for the desired annotation.

You can do this with any Java AST parser (and name resolver). I think Eclipse can provide this. Our DMS Software Reengineering Toolkit can do this. ANTLR appears to have a Java parser, but I doubt if it has Java name and type resolution.


I opted to use annotations for the runtime validation needs and then crafted a unit test to verify that all fields were annotated. This was inspired by @c0mrade .

So the annotation is @Length and requires an integer parameter. At runtime the validator iterates over fields and looks for the @Length annotation and makes sure its applied on a String field. It then looks at the length of the Strings value and makes sure it is less than or equal to the parameter for the annotation.

In a unit test I load all of the classes for my POJOs by package. I then iterate over those classes, iterate over each classes fields, and finally check and see if the field is a String and has the @Length annotation assigned. If the field is a String and does not have @Length, it adds the class and field name to a list of Strings. The assertion for the test is that this list is empty.

0

精彩评论

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

关注公众号