简体   繁体   English

java泛型参数不能应用于特定类型

[英]java generics parameter can't apply to a specific type

public class Demo {
    public String work(String s) {
        return s;
    }

    public <T> T Test(T t) {
        // common work to do !!
        // .....
        // spec work to do 
        T result = work(t);
        return result;
    }
}

Test() has some common work to do first, then specific work with respect to different type of T. The code above causes compiler errors, how can i do this ? Test() 首先有一些共同的工作要做,然后是针对不同类型的 T 的具体工作。上面的代码导致编译器错误,我该怎么做? thanks very much !非常感谢 !

There are a number of things that can cause your code not to compile here;有很多事情会导致您的代码在此处无法编译; aside from the ';', you are returning something from a void method.除了“;”之外,您还从 void 方法返回了一些东西。 Kindly post the compiler errors you're facing too, it will make things much clearer to potential responders.请发布您也面临的编译器错误,这将使潜在的响应者更清楚。

What you could possibly get away with is to create a mapping from type T to a ( unary ?) function .什么你可能逃脱是创建类型映射T的( 一元?) 功能 Then, in the test method you can look-up the type T .然后,在test方法中,您可以查找类型T If a function is registerede, apply:如果函数已注册,请应用:

public class Demo {
  private static final Map<Class<?>, UnaryOperator<?>> typeFuncs = new HashMap<>();
  static {{
    addTypeFunc(String.class, (String s) -> s); // Anonymous function.
    addTypeFunc(Integer.class, Demo::workInteger); // Function reference.
  }}

  private static <T> void addTypeFunc(Class<T> type, UnaryOperator<T> func) {
    typeFuncs.put(type, func);
  }

  private static Integer workInteger(Integer i) {
    return i;
  }

  public <T> T test(T t) {
    // common work to do !!
    // .....

    T result = null;
    UnaryOperator<T> operator = (UnaryOperator<T>) typeFuncs.get(t.getClass());
    if (operator != null) {
      result = operator.apply(t);
    }

    return result;
  }
}

Do note that the cast (UnaryOperator<T>) in test is only safe as we have total control of the relation between key and value types in the typeFuncs map.请注意, test (UnaryOperator<T>)仅是安全的,因为我们可以完全控制typeFuncs映射中的键和值类型之间的关系。

Another approach is to use reflection.另一种方法是使用反射。 Do note that reflection is a powerful tool but it comes at a cost (performance.) Perform measurements to see whether this is a viable solution is your specific case:请注意,反射是一个强大的工具,但它是有代价的(性能)。执行测量以查看这是否是一个可行的解决方案是您的具体情况:

public class Demo {
  private String work(String s) {
    return s.toUpperCase();
  }

  private Boolean work(Boolean b) {
    return !b;
  }

  public <T> T test(T t) {
    // common work to do !!
    // .....

    // Now look-up "work" method for type T. Invoke if defined.
    T result = null;
    try {
      Class<T> tType = (Class<T>) t.getClass();
      Method work = Demo.class.getDeclaredMethod("work", tType);
      if (work.getReturnType() != tType) {
        throw new NoSuchMethodException("No `work` method for type: " + tType);
      }

      result = (T) work.invoke(this, t);
    } catch (NoSuchMethodException e) {
      // NOOP - or whatever.
    } catch (IllegalAccessException | InvocationTargetException e) {
      // Method invocation failed. Handle properly.
      e.printStackTrace();
    }

    return result;
  }
}

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

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