简体   繁体   中英

In there a better way to instantiate a generic field in a class?

I am wondering if my code is correct or badly implemented. Here is the class

public class HubRequest<T extends GenericParameters> implements Serializable 
{
   private String service;
   private String method;
   private T parameters;

   public HubRequest(Class<T> myClass) {
    super();
    try {
        parameters = myClass.newInstance();
        service = parameters.getRequestService();
        method = parameters.getRequestMethod();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
   }
}

Is there a better way to initialize the "parameters" field ? I just want to automate the instantiation of that object.

由于您无法创建实例来使用new关键字键入参数 ,因此使用方法是在类内部创建type参数实例的唯一方法。

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