Java 中的泛型无效
void with Generics in Java
我有一个函数 returns 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
选项 1:
就return null
:
@Override
public Void handler(DeleteProductCommand deleteProductCommand) {
iProductService.delete(deleteProductCommand.id);
return null;
}
选项 2:
将 IProductService::delete
方法更新为 return 一些有意义的东西,例如像 Collection::remove
这样的 boolean
值:
public interface IProductService {
boolean delete(String id);
}
@Singleton
public record DeleteProductCommandHandler(IProductService iProductService)
implements IRequestHandler<DeleteProductCommand, Boolean> {
@Override
public Boolean handler(DeleteProductCommand deleteProductCommand) {
return iProductService.delete(deleteProductCommand.id);
}
@Override
public Class<DeleteProductCommand> commandType() {
return DeleteProductCommand.class;
}
}
我有一个函数 returns 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);
选项 1:
就return null
:
@Override
public Void handler(DeleteProductCommand deleteProductCommand) {
iProductService.delete(deleteProductCommand.id);
return null;
}
选项 2:
将 IProductService::delete
方法更新为 return 一些有意义的东西,例如像 Collection::remove
这样的 boolean
值:
public interface IProductService {
boolean delete(String id);
}
@Singleton
public record DeleteProductCommandHandler(IProductService iProductService)
implements IRequestHandler<DeleteProductCommand, Boolean> {
@Override
public Boolean handler(DeleteProductCommand deleteProductCommand) {
return iProductService.delete(deleteProductCommand.id);
}
@Override
public Class<DeleteProductCommand> commandType() {
return DeleteProductCommand.class;
}
}