有没有办法在不使用 implements 关键字时检查某些生成的代码是否遵循接口?

Is there a way to check if some generated code adheres to an interface when its not using the implements keyword?

我有一些无法修改的生成代码。这也意味着,我无法将 implements 关键字添加到 class 声明中。

我想实现一个可以采用该 class 实例的方法,并假设那里实现了许多方法。理想情况下,这应该由编译器强制执行

我可以在运行时使用反射来做到这一点。但我试图避免它,因为使用反射的缺点(性能、可读性……)。我还必须处理运行时错误而不是编译器错误,以防 class 不遵守接口。

示例:

  public interface Foo {
    boolean foo();
  }

  public class Bar {
    // Doesn't implement Foo interface but adheres to it
    boolean foo() {
      return true;
    }
  }

  public class Bar2 {
    // Doesn't implement or adhere to interface
    boolean bar() {
      return false;
    }
  }

现在我有了一些方法:

  public someMethod(Foo foo) {
    System.out.println(foo.foo());
  }

我可以这样称呼:

  someMethod(new Bar()); // I want something similar to this that compiles, Bar adheres to Foo
  someMethod(new Bar2()); // I'd like to have a compile-time error, Bar2 doesn't adhere to Foo

这在 Java 中可行吗?

将它们包装在实现接口的委托 class 中。

class NiceFoo implements Bar {
    private final Foo delegate;

    NiceFoo(final Foo delegate) {
        this.delegate = delegate;
    }

    @Override
    void bar() {
        delegate.bar();
    }
}

如果您不厌烦样板文件,Lombok 可以助您一臂之力。这与上面的完全等效,并且会自动委托添加到 Bar 的任何方法。如果 Foo 没有相关的方法,你会得到一个编译时错误。

@AllArgsConstructor
class NiceFoo implements Bar {
    @Delegate(types = Bar.class)
    private final Foo foo;
}