Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[aspectj-users] How to access advice aspect's fields without reflection?

I've got the following issue that I am trying to solve with AspectJ.

Given an entity class with a null @Embedded field, when trying to access it with a getter, instantiate it first if it is null.

For example:

@Entity
public class MyClass {

        @Id
private long id;

@Embedded
private Validity validity;
}


And Validity:

@Embeddable
public class Validity{
    private long from;
    private long to;
}

I'm having trouble figuring out how to best write the before() advice however.  Ideally, I'm trying to avoid using reflection for fear of slowing things down, but so far, the best I have been able to come up with is the following:

// define a pointcut for any getter method of a field with @Embedded of type Validity with any name in com.ia.domain package
pointcut embeddedGetter() : get( @javax.persistence.Embedded com.ia.domain.Validity com.ia.domain..* );
before() : embeddedGetter(){
String fieldName = thisJoinPoint.getSignature().getName();
Object obj = thisJoinPoint.getThis();
// check to see if the obj has the field already defined or is null
try{
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
if( field.get(obj) == null )
field.set(obj, new com.ia.domain.Validity() );
}
catch( IllegalAccessException | NoSuchFieldException e){}
}


Is there a better way?

Thanks,

Eric




Back to the top