Java泛型:获得泛型方法返回类型的类 [英] Java generics: get class of generic method's return type

查看:993
本文介绍了Java泛型:获得泛型方法返回类型的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我曾经写过这种方法:

  private < T>的SortedSet< T> createSortedSet(){
return new TreeSet< T>();
}

这应该是这样调用的:

 设置< String> set = createSortedSet(); 

这可以正常工作(尽管我在研究当前问题时已经看到了答案,

目前情况



无论如何,现在我正在写下面的代码(在一个类中它扩展了javax.servlet.jsp.tagext.TagSupport):

  private< T> T评估(字符串表达式){
ExpressionEvaluator evaluateator = pageContext.getExpressionEvaluator();
return evaluateator.evaluate(expression,T,null,pageContext.getVariableResolver());
}

目的是能够像这样调用:

  Integer width = evaluate(widthStr); 

我的评估方法中的代码显然不起作用。 evaluateator.evaluate()的第二个参数应该是一个Class对象。这导致我:

我的问题



如何获得泛型(返回)类的类?我应该写什么来代替T作为评估的第二个参数?



编辑:结论



Nicolas好像是对的,这是不可能完成的,我需要通过这个类作为我的方法的一个参数。好处在于,由于他的解决方案使参数在泛型上得到了参数化,所以我得到了对该参数的编译检查。

,您必须将您的方法更改为:

 私人< T> T评估(Class< T> clazz,String表达式)

然后传递 clazz 作为第二个参数。没有你期望的那么短。


Background

I once wrote this method:

private <T> SortedSet<T> createSortedSet() {
  return new TreeSet<T>();
}

It's supposed to be called like this:

Set<String> set = createSortedSet();

This works fine (although I've seen in answers here when researching the current question that this is error-prone).

The current situation

Anyway, now I am writing the following code (in a class that extends javax.servlet.jsp.tagext.TagSupport):

private <T> T evaluate(String expression) {
  ExpressionEvaluator evaluator = pageContext.getExpressionEvaluator();
  return evaluator.evaluate(expression, T, null, pageContext.getVariableResolver());
}

The purpose is to be able to call this like:

Integer width = evaluate(widthStr);

The code in my evaluate method obviously doesn't work. The second argument to evaluator.evaluate() is supposed to be a Class object. This leads me to:

My question

How can I get the Class of a generic (return) type? What should I write in place of T as the second argument to evaluate?

EDIT: Conclusion

Nicolas seems to be right, it can not be done and I need to pass the class as an argument to my method. The upside is that since his solution makes the argument parametrized on the generic type I get a compilation check on that argument.

解决方案

Unfortunately, you will certainly have to change your method to:

private <T> T evaluate(Class<T> clazz, String expression)

and then pass clazz as your second parameter. Not as short as you expected.

这篇关于Java泛型:获得泛型方法返回类型的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆