有什么方法可以在没有反射的情况下访问方面的目标对象字段(给定一个getter切入点)?



我有以下问题,我试图解决与AspectJ。

给定一个带有null @Embedded字段的实体类,当试图用getter访问该字段时,如果该字段为null,则首先实例化它。例如:这将确保getXXXX永远不会返回空值。

例如:

@Entity
public class MyClass {
        @Id
    private long id;
    @Embedded
    private Validity validity;
}

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

我有麻烦弄清楚如何最好地写before()建议。理想情况下,我尽量避免使用反射,以免放慢速度,但到目前为止,我能想出的最好方法如下:

// 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){}
}

但是我建议使用反射来访问字段值。有没有办法做到这一点而不反思?

使用around建议,您可以仅在需要初始化时才需要反射:

Object around(): embeddedGetter() {
    Object value = proceed();
    if (value == null) {
        String fieldName = thisJoinPoint.getSignature().getName();
        Object obj = thisJoinPoint.getThis();
        try{
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(obj, value = new Validity() );
        }
        catch( IllegalAccessException | NoSuchFieldException e){e.printStackTrace();}           
    }
    return value;
}

最新更新