import java.lang.reflect.Field; import org.aspectj.lang.reflect.FieldSignature; public privileged aspect FieldChangeMonitorAspect { void around(Sample sample): set(int Sample.x) && target(sample) { FieldSignature fieldSignature = (FieldSignature) thisJoinPoint.getSignature(); Field field = fieldSignature.getField(); int oldValue = sample.x; int newValue = ((Integer)thisJoinPoint.getArgs()[0]).intValue(); proceed(sample); int actualNewValue = sample.x; System.out.printf("changed field %s: old value=%d, new value=%d, " + "actual new value=%d\n", field, oldValue, newValue, actualNewValue); } }
import java.lang.reflect.Field; import org.aspectj.lang.reflect.FieldSignature; public aspect FieldChangeMonitorAspectWithReflection { void around(Sample sample): set(int Sample.x) && target(sample) { FieldSignature fieldSignature = (FieldSignature) thisJoinPoint.getSignature(); Field field = fieldSignature.getField(); try { Object oldValue = field.getInt(sample); Object newValue = thisJoinPoint.getArgs()[0]; proceed(sample); Object actualNewValue = field.get(sample); System.out.printf("changed field %s: old value=%d, new value=%d, " + "actual new value=%d\n", field, oldValue, newValue, actualNewValue); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } }
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()); }
Field field = sig.getField(); field.setAccessible(true);
Field field = fieldSignature.getField(); if (field == null) field = SecurityActions.findField(clazz, signature.getName());