我有一个返回void的函数
public interface IProductService {
void delete(String id);
}
通用方法
public interface IRequestHandler<C , R> {
R handler(C c);
Class<C> commandType();
}
通用接口的实现
@Singleton
public record DeleteProductCommandHandler(IProductService iProductService)
implements IRequestHandler<DeleteProductCommand, Void> {
@Override
public Void handler(DeleteProductCommand deleteProductCommand) {
return iProductService.delete(deleteProductCommand.id);
}
@Override
public Class<DeleteProductCommand> commandType() {
return DeleteProductCommand.class;
}
}
我该如何在 IRequestHandler<DeleteProductCommand, Void>
中使用void,以便将iProductService.delete(deleteProductCommand.id);
中的void进行映射?
handler
方法包含两个语句:1)简单的iProductService.delete(...)
;2)和return null;
。 - terrorrussia-keeps-killingNull
不是返回类型,而是Void
。但是Void
只有一个可能的值——null
。所以你要返回的就是它。你可以通过其他基本类型的包装类类比来理解这一点。例如,Integer
对应于每个int
类型的值都有一个相应的值,再加上特殊的值null
。所有基本类型的包装类都是如此。由于void
没有任何值,因此Void
具有所有(没有)这些值,加上null
。 - Brian GoetzInteger
是int
类型的相应引用类型。对于每个int
值(共2^32个),都有一个相应的Integer
值,此外Integer
还可以取值为null
。Void
是void
类型的相应引用类型。对于每个void
值(共零个),都有一个相应的Void
值,此外Void
也可以取值为null
。因此,null
是Void
唯一有效的取值。如果想要能够返回任何类型的值,请将返回类型设为Object
。 - Brian Goetz