繁体   English   中英

在运行时获取 Lambda 表达式的某种表示形式

[英]Getting some kind of representation of a Lambda Expression at runtime

我想用这样的东西来检查一些条件,但问题是我需要知道哪个条件失败并记录异常,这种方式确实实现了它但依赖于知道在代码中检查它的 position这不理想,还有其他更好的方法吗? (无需更长时间地拨打 function)

matchOrThrow(
        () -> 1 == 2,
        () -> 1 == 1,
        () -> a > b,
        () -> c == null
);
public static void matchOrThrow(BooleanSupplier... conditions) {
    int i = 1;
    for (BooleanSupplier condition : conditions) {
        if (Boolean.FALSE.equals(condition.getAsBoolean())) {
            throw new CustomException("Condition check n_" + i + " failed");
        }
        i++;
    }
}

您可能有兴趣查看Decorator 设计模式

也就是说,您可以创建您选择的 Functional 接口的装饰实现。 看起来PredicateBooleanSupplier更适合,因此下面的示例说明了一个抛出的 Predicate,它需要一个谓词、目标异常的生产者、消息和记录器 arguments 及其test()委托给包装谓词的实现评估病情。

trowing Predicate 的实例可以在需要 Predicate 的任何地方使用。

public class ThrowingLoggPredicate<T> implements Predicate<T> {
    private Predicate<T> predicate;
    private Function<String, RuntimeException> exceptionFactory;
    private String messageShort;
    private String format;
    private Logger logger;
    
    public ThrowingLoggPredicate(Predicate<T> predicate,
                                 Function<String, RuntimeException> exceptionFactory,
                                 String messageShort, String format,
                                 Logger logger) {
        
        this.predicate = predicate;
        this.exceptionFactory = exceptionFactory;
        this.messageShort = messageShort;
        this.format = format;
        this.logger = logger;
    }
    
    public boolean test(T t) {
        if (!predicate.test(t)) {
            RuntimeException e = exceptionFactory.apply(messageShort);
            String messageVerbose = String.format(format, t);
            logger.log(Level.ERROR, messageVerbose, e);
            throw e;
        }
        return true;
    }
    
    public static <T> boolean allMatch(Collection<Predicate<T>> predicates, T t) {
        
        return predicates.stream().allMatch(p -> p.test(t));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM