简体   繁体   中英

Correct way to instantiate a generic class

Weak in generic, please go easy!
I have some base and derived classes structured as below via 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:

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.

What would be the right way to create specific objects of ProcessingNode ?

You can't decide T has to be CHDAPICommand or MHDAPICommand inside the method cacheProcessingNodeManager() . You can only decide T when declaring class and method.

You can create specific objects of ProcessingNode in two ways.

  1. use Wild Card Generic
    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
        }
    }
  1. declaring Generic with method and use upcasting
    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
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM