我尝试使用 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){}
}
但我的建议是使用反射来访问字段值。有没有什么方法可以在不反射(reflection)的情况下做到这一点?
最佳答案
通过周围建议,您可以仅在需要初始化时才需要进行反射:
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;
}
关于java - 有什么方法可以在不反射的情况下访问方面的目标对象字段(给定吸气切入点)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623287/