简体   繁体   中英

Java: Get class type of return object of generic supplier

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

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());
  }
}

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