@FunctionalInterface
public interface ServiceCaller {
void callService();
}
//common method to execute any service call
public void executeService(ServiceCaller serviceCaller) {
//do common things
//i want to access dbValidationRequest/apiValidationRequest here for logging purpose
try {
serviceCaller.callService();
} catch (Exception ex) {
//do common things
LogUtils.log(logger, ex);
}
//do common things
}
//my clients call this
public void validateFromDb(DbValidationRequest dbValidationRequest){
commonUtils.executeService(()-> dbValidationService.validate(dbValidationRequest));
}
//my clients call this
public void validateFromApi(ApiValidationRequest apiValidationRequest){
commonUtils.executeService(()-> apiValidationService.validate(apiValidationRequest));
}
这是Java Spring Application的控制器。在 executeService 方法内部,我传递了 ServiceCaller 接口的实例。我使用此方法从控制器调用所有服务。如果我使用智能IDEA进行评估,则可以在executeService方法内部查看dbValidationRequest / apiValidationRequest的值(如arg $ 2,请参见附图)。我需要打印这些对象以用于记录目的,我也根本不想使用方面。我怎样才能做到这一点。如果智能IDEA可以看到这些值,为什么不能以编程方式进行?
答案 0 :(得分:2)
arg$1
和arg$2
可以视为类的字段,因此可以通过反射获得。
String var1 = "Content Var 1";
String var2 = "Content Var 2";
Supplier<String> stringSupplier = () -> var1 + var2;
Field[] declaredFields = stringSupplier.getClass().getDeclaredFields();
for (Field f : declaredFields) {
f.setAccessible(true);
System.out.println(
"Field Name: " + f.getName() +
", value: " + f.get(stringSupplier)
);
}
// Field Name: arg$1, value: Content Var 1
// Field Name: arg$2, value: Content Var 2