简体   繁体   English

如何动态推断 Java 上的方法类型?

[英]How can I infer the type of the method on Java dynamically?

I have this two classes, using generics:我有这两个类,使用泛型:

public Response version1(Parameters params) {
   Supplier<Response> s = () -> getResponse(params);
   return unversioned(params, s);
}

public Response2 version2(Parameters params) {
   Supplier<Response2> s = () -> getResponse2(params);
   // s.get().getData(); Here, I am able to get the Data, because it knows it's from a Response2 class.
   return unversioned(params, s);
}

These two generics are used for me to not have to duplicate every single line of code, as the methods are pretty much the same, just one line of code is different, which is the return type.这两个泛型用于我不必复制每一行代码,因为方法几乎相同,只是一行代码不同,即返回类型。 So, when I call the generics:所以,当我调用泛型时:

private <T> T unversioned(Parameters parameters, Supplier<T> supplier) {
    T result = supplier.get();
}

When I try to get the result.getData() method, it does not understand.当我尝试获取result.getData()方法时,它不明白。 Because it does not infer the type.因为它不推断类型。 How can I do that?我怎样才能做到这一点?

What you could do is add bounds to the generic type of your unversioned method.你可以做的是为你的非unversioned化方法的泛型类型添加边界。

private <T extends DataProvider> T unversioned(Parameters parameters, Supplier<T> supplier) {
  // logic
}

This, however, requires you to have your response objects implement an interface:然而,这需要你让你的响应对象实现一个接口:

public interface DataProvider {
  /*
   * Not sure what the return type of getData is, so used String for illustrative purposes
   */
  String getData(); 
}

In case your response objects need to have different return values for getData you could further generify the interface.如果您的响应对象需要为getData提供不同的返回值,您可以进一步生成接口。

public interface DataProvider<T> {
  T getData(); 
}

This requires a slight tweak of the unversioned method:这需要对unversioned化的方法稍作调整:

private <T extends DataProvider<?>> T unversioned(Parameters parameters, Supplier<T> supplier) {
  // logic
}

And you can now define your response objects as follows:您现在可以按如下方式定义响应对象:

public class StringResponse implements DataProvider<String> {
  @Override
  public String getData() {
    // logic
  }
}

public class IntegerResponse implements DataProvider<Integer> {
  @Override
  public Integer getData() {
    // logic
  }
}

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

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