代码之家  ›  专栏  ›  技术社区  ›  GhostCat

如何不抛出一般指定的异常?

  •  21
  • GhostCat  · 技术社区  · 6 年前

    我创建了一个“生产者”接口(分别与方法引用一起使用,以便在单元测试中轻松模拟):

    @FunctionalInterface
    public interface Factory<R, T, X extends Throwable> {
        public R newInstanceFor(T t) throws X;
    }
    

    我这样创建的,作为我的第一个用例,实际上必须抛出一些检查 WhateverException .

    但是我的第二个用例没有X可以抛出。

    我能想到的让编译器高兴的最好方法是:

    Factory<SomeResultClass, SomeParameterClass, RuntimeException> factory;
    

    它编译了,做了我需要的,但仍然很难看。在声明特定实例时,是否有一种方法可以保持该单个接口,但不提供X?

    6 回复  |  直到 6 年前
        1
  •  12
  •   Eugene    6 年前

    BinaryOperator BiFunction

        2
  •  12
  •   Leo Aso    6 年前

    public interface DefaultExceptionFactory<R, T>
            extends Factory<R, T, RuntimeException>
    
        3
  •  5
  •   M. Prokhorov    6 年前

    public interface Factory<T, R, X> {
    
        public R newInstanceFor(T arg) throws X;
    
        public static Factory<R, U, AssertionError> neverThrows(Factory<U, V, ?> input) {
            return u -> {
                try {
                    return input.newInstanceFor(u);
                }
                catch(Throwable t) {
                    throw new AssertionError("Broken contract: exception thrown", t);
                }
            };
        }
    }
    

    class MyClass {
        Factory<MyInput, MyOtherClass, AssertionError> factory;
    
        MyClass(Factory<MyInput, MyOtherClass, ?> factory) {
            this.factory = Factory.neverThrows(factory);
        }
    
        public void do() {
          factory.newInstanceFor(new MyInput()).do();
        }
    }
    

        4
  •  3
  •   Beno    6 年前

    @FunctionalInterface
    public interface Factory<R, T> {
        public <X extends Throwable> R newInstanceFor(T t) throws X;
    }
    
        5
  •  0
  •   foundationer    6 年前

    @SneakyThrows

    @FunctionalInterface
    public interface Factory<R, T> {
    
        @SneakyThrows
        R newInstanceFor(T t);
    }
    

        6
  •  -3
  •   Yogesh Pandit    6 年前

    @FunctionalInterface
    public interface Factory<R, T> {
        public R newInstanceFor(T t) throws Throwable;
    }
    

    推荐文章