Java: Get class type of return object of generic supplier

3k views Asked by At

Let's assume the following definition is given:

final Supplier<MyClass> supplier = MyClass::new;

Is there a way I can get MyClass.class without actually invoking .get() on the supplier?

Why? I have to know the specified class to make some logical decisions. Based on this, I might need to find another constructor in MyClass which has a parameter and the only knowledge I have of the target class is a supplier of this type. Of course I could just invoke .get() and go from there, like this:

final MyClass obj = supplier.get().getClass().getConstructor(MyParameter.class).newInstance(..);

But using this before doing my intermediate steps might result in an unnecessary object creation

1

There are 1 answers

2
goedi On BEST ANSWER

You can do something like below. It is necessary to add Guava as a dependency.

import java.lang.reflect.Type;
import java.util.function.Supplier;

import com.google.common.reflect.TypeToken;

public abstract class MySupplier<T> implements Supplier<T> {

  private final TypeToken<T> typeToken = new TypeToken<T>(getClass()) { };
  private final Type type = typeToken.getType();

  public Type getType() {
    return type;
  }
}

public class Test {

  public static void main(String[] args) {

    Supplier<String> supplier = new MySupplier<String>() {
      @Override
      public String get() {
        return new String();
      }
    };
    System.out.println(((MySupplier) supplier).getType());
  }
}