[英]Correct way to instantiate a generic class
Weak in generic, please go easy!弱通用,请 go 容易!
I have some base and derived classes structured as below via generics我有一些通过 generics 结构如下的基类和派生类
public abstract class ProcessingNode<T extends APICommand> extends Node {
}
public class CustomerProcessingNode extends ProcessingNode<CHDAPICommand> {
}
public class MerchantProcessingNode extends ProcessingNode<MHDAPICommand> {
}
public class APICommand {
}
public class CHDAPICommand extends APICommand {
}
public class MHDAPICommand extends APICommand {
}
Now, during server start i would want to pick the right ProcessingNode
and cache it as below:现在,在服务器启动期间,我想选择正确的ProcessingNode
并将其缓存如下:
private void cacheProcessingNodeManager() throws ListenerException {
// throws Unexpected Bound error
ProcessingNode<T extends APICommand> processingNodeManager = null;
if (condition1 is true){
// throws "required ProcessingNode<T> but found CustomerProcessingNode"
processingNodeManager = new CustomerProcessingNode();
}
else if (condition2 is true){
// throws "required ProcessingNode<T> but found MerchantProcessingNode"
processingNodeManager = new MerchantProcessingNode();
} else {
// some exception
}
// cache processingNodeManager
}
but i get 2 error as highlighted in comments above.但我得到了上面评论中突出显示的 2 个错误。
What would be the right way to create specific objects of ProcessingNode
?创建ProcessingNode
特定对象的正确方法是什么?
You can't decide T
has to be CHDAPICommand
or MHDAPICommand
inside the method cacheProcessingNodeManager()
.您不能决定T
必须是方法cacheProcessingNodeManager()
中的CHDAPICommand
或MHDAPICommand
。 You can only decide T
when declaring class and method.您只能在声明 class 和方法时决定T
You can create specific objects of ProcessingNode
in two ways.您可以通过两种方式创建ProcessingNode
的特定对象。
public void cacheProcessingNodeManager() throws Exception {
ProcessingNode<? extends APICommand> processingNodeManager = null;
if (condition1 is true){
processingNodeManager = new CustomerProcessingNode();
} else if (condition2 is true){
processingNodeManager = new MerchantProcessingNode();
} else {
// some exception
}
}
public <T extends APICommand>void cacheProcessingNodeManager() throws Exception {
ProcessingNode<T> processingNodeManager = null;
if (condition1 is true){
processingNodeManager = (ProcessingNode<T>) new CustomerProcessingNode();
} else if (condition2 is true) {
processingNodeManager = (ProcessingNode<T>) new MerchantProcessingNode();
} else {
// some exception
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.