简体   繁体   English

Java:获取通用供应商的返回对象的类类型

[英]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? 有没有办法在没有实际调用供应商的.get()情况下获取MyClass.class

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. 基于此,我可能需要在MyClass找到另一个具有参数的构造函数,并且我对目标类的唯一知识就是这种类型的供应商。 Of course I could just invoke .get() and go from there, like this: 当然我可以调用.get()并从那里开始,像这样:

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. 有必要添加Guava作为依赖项。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM