gpt4 book ai didi

java - Java 中的泛型无效

转载 作者:行者123 更新时间:2023-12-05 03:32:33 27 4
gpt4 key购买 nike

我有一个返回void的函数

public interface IProductService {
void delete(String id);
}

通用方法

public interface IRequestHandler<C , R> {
R handler(C c);
Class<C> commandType();
}

通用接口(interface)的实现

 @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:

只返回null:

@Override
public Void handler(DeleteProductCommand deleteProductCommand) {
iProductService.delete(deleteProductCommand.id);
return null;
}

选项 2:

更新 IProductService::delete 方法以返回有意义的内容,例如像 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;
}
}

关于java - Java 中的泛型无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70451216/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com