2

I have an interface, parametrized by <V> and would like to pass the type parameter to a method like this:

public interface MyInterface<V extends BaseClass> {

  <T> T myGenericMethod(Class<T> clazz);

  default void run() {
    ...
    String s = ((BaseClass) myGenericMethod(V)).getStringValue(); // <- V can not be resolved to a variable
    ...
  }

}

As a workaround I use now method, returning the class, which I'd like to avoid:

Class<?> getType();
meridbt
  • 304
  • 1
  • 11
  • 3
    `V` is a type argument that is not available as a variable or type. Java doesn't have reified generics and it is difficult-to-impossible to find out what V is at runtime. A workaround is to ask the programmer to provide a generic class as the parameter: ` S myGenericMethod(Class clazz)`. – akarnokd Jun 16 '22 at 08:01
  • 2
    You're replacing the `S` of the interface, with an unrelated `S` for the generic method. Did you mean `S myGenericMethod(...)` instead (so without the `` on the method definition)? Also, it is not really clear to me what you're trying to achieve here. – Mark Rotteveel Jun 16 '22 at 08:02
  • 1
    Fo me it is obvious that you try to "solve some problem"/"design some functionality" in wrong way, that's why you run into these weird problems. But there is not enough information on what functionality you want to achieve. Please explain what you need then probably you will get the right answer with the right solution. – Krzysztof Cichocki Jun 16 '22 at 08:23
  • @MarkRotteveel, you're right, I've mistaken. Edited the code, thank you. In my case, `myGenericMethod` implementation uses Jackson to convert object to a certain class, which differs in the interface implementations. – meridbt Jun 16 '22 at 08:34
  • 1
    A class (`Class`) and a type (``) are not the same thing. A class _has_ a type, but _isn't itself_ a type. Types are compile-time only; gone by the time you actually run the program, so you will not be able to convert `` into a `Class` at runtime. – Kaan Jun 16 '22 at 15:31

0 Answers0