简体   繁体   English

如何找到Java泛型类的类对象?

[英]How to find the class object of Java generic type?

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: 假设我有一个通用类型P ,它是一个Enum,即<P extends Enum<P>> ,我想从字符串中获取Enum值,例如:

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

This will get a compile error because P.class is invalid. 这将导致编译错误,因为P.class无效。 So what can I do in order to make the above code work? 那么,为了使上述代码有效,我该怎么办?

You must have a runtime instance of this generic type somewhere so that you can just grab the declaring class by Enum#getDeclaringClass() . 您必须在某处具有此泛型类型的运行时实例,以便您可以通过Enum#getDeclaringClass()获取声明类。 Assuming that you've declared P p somewhere as a method argument, here's an example. 假设你已经将P p声明为某个方法参数,这是一个例子。

Eg 例如

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

There is no way in Java. Java中没有办法。 Generic types are erased and converted to Object in byte code. 擦除通用类型并将其转换为字节代码中的Object The generic type ('P' in your case) is not a real class but just a placeholder. 泛型类型(在您的情况下为“P”)不是真正的类,而只是占位符。

Have a look at this question with great answers on type erasure. 有关类型擦除的好答案,请查看此问题

Java implements generics using something called type erasure. Java使用称为类型擦除的东西来实现泛型。 What that means is the actual generic parameter is erased at runtime. 这意味着实际的通用参数在运行时被擦除。 Thus, you cannot infer type information from generic type parameters. 因此,您无法从泛型类型参数中推断出类型信息。

You can get it at runtime by having the caller or some configuration provider it. 您可以通过让调用者或某个配置提供程序在运行时获取它。 For example, you could have Spring or whatever configure this. 例如,您可以使用Spring或其他任何配置。

class Converter<P extends Enum> {
    private Class<P> type;

    //setter and getter

    public P valueOf(String name) {
        return Enum.valueOf(type, name);
    }
}

And then configure it wherever it's needed. 然后在需要的地方配置它。

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

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