简体   繁体   中英

Java annotation-based code injection without altering the annotated code

There is a Java application and I have no permission to alter the Java code apart from annotating classes or methods (with custom or existing annotations). Using annotations and annotations only I have to invoke code which means that every time an instance of an annotated class is created or an annotated method is called, some extra Java code must be executed (eg a call to a REST Webservice). So my question is: how can I do this?

In order to prevent answers that I have already checked I will give you some solutions that seem to work but are not satisfying enough.

  1. Aspect Oriented Programming (eg AspectJ) can do this (execute code before and after the call of an annotated method) but I don't really want the runtime overhead.

  2. Use the solution provided here which actually uses reflection. This is exactly what I need only that it alters the initial code further than just annotating and so I cannot use it.

  3. Use annotation processor for source code generation as suggested here by the last answer. However, still this means that I will alter the source code which I don't want.

What I would really like is a way to simply include a Java file that somehow will execute some Java lines every time the annotated element will be triggered.

Why not skip annotations completely and use byteman to inject code at runtime into the entry points of your code.

I have to agree with the comment above though, that this sort of restriction is ridiculous and should be challenged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM