如何用泛型返回类型推断方法的特定返回类型? [英] How to infer the specific return type of a method with a generic return type?

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

问题描述

给出以下界面:

interface Random extends java.util.function.Supplier<Integer> { }

带有 java.util.function.Supplier

看起来像这样(缩写):

with java.util.function.Supplier looking like this (abbreviated):

public interface Supplier<T> { T get(); }

现在考虑以下几点:

java.lang.reflect.Method get = Random.class.getMethod("get");
System.out.println(get.getReturnType()); // prints `class java.lang.Object`
System.out.println(get.getGenericReturnType()); // prints `T`

如何推断返回类型实际上应该是 java.lang.Integer ?

How can I infer that the return type should actually be java.lang.Integer?

推荐答案

您可能可以使用下面的代码执行此操作.这里的想法是通用类型信息可能在字节码中可用,并且可以在运行时访问.请参阅下面的链接以获取更多详细信息.

You can probably do this with something like below code. The idea here is that the generic type information is potentially available in the byte code and can be accessed at runtime. Refer the link below for more details.

ParameterizedType parameterizedType = (ParameterizedType) subClass.getGenericSuperclass();
09
  return (Class<?>) parameterizedType.getActualTypeArguments()[parameterIndex];

https://www.javacodegeeks.com/2013/12/advanced-java-generics-retreiving-generic-type-arguments.html

在线上还有其他一些有用的文章对此进行了描述.

There are some other useful articles online which describe this too.

这篇关于如何用泛型返回类型推断方法的特定返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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