如何找到Java泛型的类对象? [英] How to find the class object of Java generic type?

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

问题描述

假设我有一个通用类型 P ,它是一个枚举,即< P扩展了Enum< P>> ,我想从字符串中获取Enum值,例如:

Assume I have a generic type P which is an Enum, that is <P extends Enum<P>>, and I want to get the Enum value from a string, for example:

String foo = "foo";
P fooEnum = Enum.valueOf(P.class, foo);

这将导致编译错误,因为 P.class 无效。那么,为了使上面的代码起作用,我该怎么办?

This will get a compile error because P.class is invalid. So what can I do in order to make the above code work?

推荐答案

您必须在某处拥有这种通用类型的运行时实例。因此您可以通过 Enum#getDeclaringClass() 。假设您在某个地方声明了 P p 作为方法参数,下面是一个示例。

You must have a runtime instance of this generic type somewhere so that you can just grab the declaring class by Enum#getDeclaringClass(). Assuming that you've declared P p somewhere as a method argument, here's an example.

Eg

public static <P extends Enum<P>> P valueOf(P p, String name) {
    return Enum.valueOf(p.getDeclaringClass(), name);
}

这篇关于如何找到Java泛型的类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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