I am assuming you are talking about runtime code injection, and not compile time. For runtime code injection you need to use a framework that does injection of code (like AOP, or Spring which internally uses AOP) or you need to build your own mechanism
The basic idea behind injecting code is that you create a proxy class. Let me take Spring as an example. Basically, what happens behind the scenes Spring creates a proxy class at runtime that delegates to the real object
So, let's say you have an interface for a service that gets list of users and you have an implementation of the class, and a class that uses the implmentation via the interface
Now, in an application that uses Spring, Spring injects the userService into UserController. If the service is annotatted, behind the scenes, SPring creates a class at runtime that implements Userservice and delegates to the real UserService. The class looks somewhat like this
Now, when Spring gives a userService to UserController, it gives an instance of LoggingUserServiceProxy. COntroller doesn't know that.. When controller calls getUser.. the control goes to the proxy, the proxy logs before the method, then calls the real getUsermethod, and then does some more logging
Ok, so what do you do if you are not using Spring? It depends on whether you are doing your dependency injection, or if you have factory methods.
Java provides a class called
Proxy that helps create runtime proxy classes like the one above. Look at the link. It has details. It becomes easy to plug this in your code if you the code that creates objects is centralized (like if you are using Dependency Injection
pattern, or factory pattern, or ServiceLocator pattern). Basically, the code that is responsible for instantiating objects, can inspect the object that it has created to check if it is annotated. If it is annotated, it can create the Proxy and return the proxy. Boom! you sort of implemented your own bare bones AOP.
If your object creation code is not centralized, you are out of luck.