开发者

Enforce that a code snippet is always present on a set of Java classes

开发者 https://www.devze.com 2023-02-16 13:35 出处:网络
I have to be sure that a snippet of code get executed in all public methods of classes under a certain package:

I have to be sure that a snippet of code get executed in all public methods of classes under a certain package:

public String doStuff(String a, Integer b, Context c) {
   current.put(c); <--- code that need to be executed
   // business logic
   ...
}

What would be the best approach for ensuring that that snippet of code is always present AS THE FIRST LINE of each public method?

I have considered using some static code analysis tool, such as PMD. Also, I believe compile time AOP could help. Any more idea, pointers?

I know that I can use an Aspect for that. Problem is that my application is using Spring but the classes I need to "check" are not spring managed - also, I'd like to avoid changing the server start options to enable Spring annotation based run time weaving.

EDIT: The classes I ha开发者_如何学JAVAve to enforce the code on are Akka Typed Actors.


I need to pass a "Context" object to the next layer and I'm planning to use ThreadLocal for that. The snippet has to put the current context into the threadlocal.

If you're using Spring, have you considered making the context a thread-scoped bean? If this is through a HTTP request, you can use scope="request" on the bean and Spring will manage things for you (including passing a request-scoped bean to a singleton).

You can easily create a more general thread scope.


PMD is a good option. Besides you can integrate it with IDE and all developers will be notified.

Another option is to add some step to your build process that will either modify the source code using some regular expression (or Java parser - PMD has one as well) or add some byte code generation using libraries like ASM or JavaAssist that will post process your code after it is compiled.

If you can use AspectJ then you can also use that to post-process your class files after they are compiled to check/add some code.

If you can control this class creation using some Factory implemetation, then you can create a dynamic proxy around the created instances.

0

精彩评论

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