soc
soc

Reputation: 28423

How to add a method to a class where the method name is based on an existing, annotated method in AspectJ?

Consider this code:

class DatabaseCommands {

    @Privilege(ADMIN)
    public void delete(Something thingToDelete, User currentUser) {
        /* ... */
    }
}

Currently an access check is weaved into this method, to check if currentUser has the necessary rights to execute the database command (and throws an exception if not).

What do I have to add to my AspectJ file so that a new method

public boolean deleteAllowed(Something thingToDelete, User currentUser)

is added to the class, with the same access checks, but without the execution of the command?

This use case seems to be similar to the one of adding getters/setters to fields, like

class Foo {
    @Getter @Setter
    String name = ""
}

Upvotes: 2

Views: 1465

Answers (1)

Simone Gianni
Simone Gianni

Reputation: 11662

to my knowledge, unfortunately, it's not possible add methods (called Inter Type Declarations in AspectJ) using dynamic signatures, so there is no way to create methods based on names or parameters of another method.

@Setter @Getter is not implemented using AspectJ, but using other techniques. Spring Roo will actually inspect source code, and generate source for aspects, which will then be compiled and applied to original classes. Project Lombok and others use directly ASM, BCEL or APT to instrument Java bytecode. ASM is the same toolkit used by AspectJ itself to modify (Weave in AspectJ terminology) .class files, but when used directly is much more flexible (and much more complicated) than AspectJ. APT is Sun's Annotation Processing Tool, which since Java 6 is "embedded" in the Java compiler. It can be used to "intercept" the moment Javac is compiling a method or class having certain annotations, and can be used to "inject" new code, there including a getter/setter pair, or another new method.

Upvotes: 4

Related Questions