泛型在静态方法中 [英] Generics in static methods

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

问题描述

我需要在实用程序类中添加一些方法,这些方法可以解析JSON字符串中的内容并返回一组数据。



问题在于:是这些东西的各种子类型,所以我创建了这个方法:

  public static< E extends Thing> E [] parseThingsFromJSON(String body){
return parser.fromJson(body,E []。class);

调用者如何告诉这个方法 E 是?或者有更好的方法来做到这一点?

解决方案

您需要传递它。

  public static< E extends Thing> E [] parseThingsFromJSON(String body,Class< E []> eClass){
return parser.fromJson(body,eClass);
}

泛型在很大程度上是一个编译时功能。这意味着它在运行时不可用(有一些例外)。

在这种情况下,为了使泛型在运行时可用,必须将它作为附加参数。


I need to add a method in a utility class with some static methods that parses things from a JSON string and returns an array of things.

Problem is that there are various subtypes of these things, so I created this method:

public static <E extends Thing> E[] parseThingsFromJSON(String body) {
    return parser.fromJson(body, E[].class);
}

How does the caller tell this method what E is? Or is there a better way to do this?

解决方案

You need to pass it.

public static <E extends Thing> E[] parseThingsFromJSON(String body, Class<E[]> eClass) {
    return parser.fromJson(body, eClass);
}

Generics is largely a compile time feature. This means its not available at runtime (with some exceptions)

In this case, to make to make the generic type available at runtime, you have to pass it as an additional argument.

这篇关于泛型在静态方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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