zam*_*tul 3 java lambda functional-interface
@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));
}
Run Code Online (Sandbox Code Playgroud)
这是Java Spring应用程序的控制器。在executeService方法中,我传递了ServiceCaller接口的一个实例。我使用此方法从控制器调用所有服务。如果我使用 intelliJ IDEA 进行评估,那么我可以在executeService 方法中查看 dbValidationRequest/apiValidationRequest 的值(如 arg$2,请参阅附图)。我需要打印这些对象以用于记录目的,我也根本不想使用方面。我怎样才能做到这一点。如果 intelliJ IDEA 可以看到这些值,为什么我不能以编程方式看到这些值?

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
Run Code Online (Sandbox Code Playgroud)