匿名类的多重继承
2022-08-31 10:15:13
匿名类如何实现两个(或更多)接口?或者,它如何扩展类和实现接口?例如,我想创建一个扩展两个接口的匿名类对象:
// Java 10 "var" is used since I don't know how to specify its type
var lazilyInitializedFileNameSupplier = (new Supplier<String> implements AutoCloseable)() {
private String generatedFileName;
@Override
public String get() { // Generate file only once
if (generatedFileName == null) {
generatedFileName = generateFile();
}
return generatedFileName;
}
@Override
public void close() throws Exception { // Clean up
if (generatedFileName != null) {
// Delete the file if it was generated
generatedFileName = null;
}
}
};
然后,我可以在 try-with-resources 块中将其用作延迟初始化的实用程序类:AutoCloseable
try (lazilyInitializedFileNameSupplier) {
// Some complex logic that might or might not
// invoke the code that creates the file
if (checkIfNeedToProcessFile()) {
doSomething(lazilyInitializedFileNameSupplier.get());
}
if (checkIfStillNeedFile()) {
doSomethingElse(lazilyInitializedFileNameSupplier.get());
}
}
// By now we are sure that even if the file was generated, it doesn't exist anymore
我不想创建一个内部类,因为我绝对确定除了我需要使用它的方法之外,这个类不会在任何地方使用(而且我还可能想要使用该方法中声明的可能属于类型的局部变量)。var