How to pass a class level generic to a method

user1220373 :

I have a class which accepts a generic parameter

class MyClass<D> {

  public void myMethod() {

   }

}

Now I have an external API method with the following signature?

public static <T> T apiMethod​(String str, java.lang.Class<T> classOfT) {
}

I want something like the below, but I'm getting compilation error.

class MyClass<D> {

      public void myMethod(String str) {
            ApiClass.apiMethod​(str,D); 

       }

 }

Any idea of how can I achieve that?

Michael :

You can't do that. The best you can do is defer the responsibility to the caller, making them pass the class to the constructor.

class MyClass<D> {

   private Class<D> clazz;

   MyClass(Class<D> clazz) { 
       this.clazz = clazz;
   }

   public void myMethod() {
       ApiClass.apiMethod​(str, clazz); 
   }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=299838&siteId=1