简体   繁体   中英

Figuring out types that were used to instantiate template in Java

Is it possible that the type "Input" used for an instance of MyClass<Input> is actually Integer for this instance I'm running right now? For example, I have:

class MyProcessor<Input, Output> {

  public void initialize() {
    if (Long.class.isAssignableFrom(Input.class))
    ....
  }
}

IntelliJ tells me I can't "select from a type variable" on "Input.class".

You cannot find the generic type since the information about it is lost at the runtime .

It's merely a hint used for casting on templated class.

If you are willing to pass the type through the constructor, then you can hold onto that type in a field, eg

public class MyClass<T> {
    private final Class<T> clazz;

    ...

    public MyClass(Class<T> clazz, ...) {
        this.clazz = clazz;
        ...
    }

    ...

    public void initialize() {
        if (Long.class.isAssignableFrom(clazz)) 
        ....
    }

}

Other than that the information gets thrown away due to type erasure

I seem to have found a solution for a specific case that contradicts the previous answers. Here is the code (it works):

interface Processor<I,O>
{
  public O process();
}

abstract class SimpleProcessImpl<I,O> implements Processor<I,O>
{
  List<Processor> _upstream = new ArrayList<Processor>();

  @SuppressWarnings("unchecked")
  public I getInput()
  {
    Object value = _upstream.get(0).process();

    ParameterizedType t = (ParameterizedType) getClass().getGenericSuperclass();
    Class dstClass = (Class) t.getActualTypeArguments()[0];
    Class srcClass = value.getClass();

    System.out.println(srcClass.getName() + " -> " + dstClass.getName());

    if (dstClass == String.class && srcClass == String.class) {
      return (I) value;
    }

    if (dstClass == String.class) {
      return (I) value.toString();
    }

    if (srcClass == String.class && dstClass == Integer.class) {
      String valueStr = (String) value;
      Integer valueInt = Integer.parseInt(valueStr);
      return (I) valueInt;
    }

    if (srcClass == String.class && dstClass == Long.class) {
      String valueStr = (String) value;
      Long valueInt = Long.parseLong(valueStr);
      return (I) valueInt;
    }

    return (I) value;
  }
}

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