我有一些我无法修改的生成代码。这也意味着,我无法将implements关键字添加到类声明中。
我想实现一个方法,可以采用该类的实例,并假设在那里实现了许多方法。理想情况下,这应该由编译器强制执行
我可以在运行时使用反射来做到这一点。但我试图避免它,因为使用反射的缺点(性能,可读性,......)。在类不遵守接口的情况下,我还必须处理运行时错误而不是编译器错误。
例:
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 NiceFoo implements Bar {
private final Foo delegate;
NiceFoo(final Foo delegate) {
this.delegate = delegate;
}
@Override
void bar() {
delegate.bar();
}
}
如果你不能被样板困扰,龙目岛就可以解救。这完全等同于上面的内容,并将自动委托添加到Bar的任何方法。如果Foo没有相关方法,则会出现编译时错误。
@AllArgsConstructor
class NiceFoo implements Bar {
@Delegate(types = Bar.class)
private final Foo foo;
}