Java: instantiate parametrized class by passing types as method parameter

57 Views Asked by At

My problem is that there is a generic class called TypedProducer<K, V> for key and value and I do have to instantiate it from configuration (let's say config tells me during runtime that key is Integer and value is String in configuration during runtime but it can be any Object subtype really) so I don't know the types beforehand.

How can I instantiate TypedProducer by passing parameters? Or even create SourceTypedClassProvider<keyType, valueType> in the first place from .class objects?

public class SourceTypedClassProvider {

  public static TypedProducer<?, ?> instantiateTypedProducer(
      Class<?> keyType, Class<?> valueType) {
    //should return instance of TypedProducer<Integer, String>
  }
}

I know there's something like TypeToken in guava, but would it help me at all in this scenario when types have to be first gotten from configuration?

EDIT: To be honest TypedProducer implementation shouldn't make a difference (you can treat it as if I were instantiating e.g. a Map<K, V>) but if it makes it easier part of the implementation below:

public class TypedProducer<K, V> {
  ExternalApiProducer<K, V> externalApiProducer;

  public TypedProducer() {
    externalApiProducer = new ExternalApiProducer<>();
  }

  public Map<K, V> produceRecords() {
    //some code that calls externalApiProducer to produce records 
  }
}
1

There are 1 best solutions below

4
erickson On

Given the code shown in your question, this works:

public static TypedProducer<?, ?> instantiateTypedProducer(Class<?> keyType, Class<?> valueType) {
    return new TypedProducer<>();
}

I would guess that having a TypedProducer<?, ?> (with unspecified bounds) is useless though. Don't you want to end up with something like TypedProducer<Integer, String>?


Given the code you've shown for TypedProducer and ExternalApiProducer, clients can simply do this:

TypedProducer<Integer, String> producer = new TypedProducer<>();

There's no need for a instantiateTypedProducer() method, or to have references to the Integer or String classes.

You'll need to provide enough code to explain why you can't use the obvious and straightforward approach. Justify your need to complicate things.