Irakli
Irakli

Reputation: 983

AspectJ - pass interface instance variable to pointcut

I need to pass @interface instance variable value to pointcut and the method but wasn't able to find anything on google.

here is what I have so far:

pointcut:

pointcut auditField(Object t, Object value): set(@ge.shemo.anotations.CaptureChanges * * ) && args(value) && target(t);

before (Object target, Object newValue, FieldChangeName fieldName): 
        auditField(target, newValue,fieldName) {
    FieldSignature sig = (FieldSignature) thisJoinPoint.getSignature();
    Field field = sig.getField();
    field.setAccessible(true);
    Object oldValue;
    try {
        oldValue = field.get(target);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Failed to create audit Action", e);
    }
    System.out.println("changed from " + oldValue + " to " + newValue);
}

and interface:

@Retention(RUNTIME)
@Target(value = FIELD)
public @interface CaptureChanges {
    MethodType fieldType();
}

UPDATED

public enum MethodType {
    NAME(FieldChangeType.STRING),
    ID(FieldChangeType.STRING),
    FIRST_NAME(FieldChangeType.STRING),
    LAST_NAME(FieldChangeType.STRING);

    private FieldChangeType type;

    private FieldChangeName(FieldChangeType type) {
        this.type = type;
    }

    public FieldChangeType getType() {
        return this.type;
    }
}
public enum FieldChangeType {
    ENUM, STRING
}

I want to get the value of 'FieldChangeMethod method' from @interface CaptureChanges and use it in before() function.

How can I do this?

Upvotes: 2

Views: 519

Answers (1)

Nándor Előd Fekete
Nándor Előd Fekete

Reputation: 7098

While it's unclear to me what you're trying to achieve with the MethodType and FieldChangeType classes, here's a way to access the value of the @CaptureChanges annotation when a field value is about to change:

pointcut auditField(Object t, Object value, CaptureChanges captureChanges): 
    set(* *) && @annotation(captureChanges) && args(value) && target(t);

before (Object target, Object newValue, CaptureChanges captureChanges): 
        auditField(target, newValue, captureChanges) {

    FieldSignature sig = (FieldSignature) thisJoinPoint.getSignature();
    Field field = sig.getField();
    field.setAccessible(true);
    Object oldValue;
    try {
        oldValue = field.get(target);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Failed to create audit Action", e);
    }
    System.out.println("changed from " + oldValue + " to " + newValue 
            + ", fieldType=" + captureChanges.fieldType()
            + ", fieldChangeType=" + captureChanges.fieldType().getType());
}

Upvotes: 2

Related Questions