用它的泛型类型返回一个Class实例

用它的泛型类型返回一个Class实例

本文介绍了用它的泛型类型返回一个Class实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个简单的例子,演示了我正在运行的与类型擦除相关的问题。我有这样的一个类:

 是 Class 。我查看了,并且 getRawType 方法看起来很有前途,但它返回 Class< ;?超级T> 。



我暂时有一个解决方法,看起来像这样:

  public class ThingListMap {
private Map< String,List< Thing>> thingListMap;

...
}

我只是使用 ThingListMap 作为泛型类型参数。



另一个可能的解决方法是执行强制转换:

  public Class< Map< String,List< Thing>>>新的HashMap< String,List< Thing>>()。getClass();返回类型的值。 
}

有没有更优雅的方式来做到这一点?



编辑:为回应其中一个答案,我无法更改 handledType 方法的签名我不拥有或控制它的源代码。

解决方案

由于某些原因,Java不允许您将 Map.class 直接到 Class< Map< String,List< Thing>>> 。这是一个未经检查的演员。

但是将它投出两次是合法的,首先是 Class < / code>然后到 Class< Map< String,List< Thing>>>< / code>

  return(Class   

作为未经检查的转换,您可能需要添加 @SuppressWarnings(unchecked )。

Here's a simple example that demonstrates a type-erasure-related issue I am running into. I have a class like this:

public abstract class AbstractHandler<T> {

    ...
    public abstract Class<T> handledType();
}

Then I have this implementation:

public class ConcreteHandler extends AbstractHandler<Map<String, List<Thing>>> {

    @Override
    public Class<Map<String, List<Thing>>> handledType() {
        //what do I return here?!
    }
}

I can't return Map<String, List<Thing>>.class, since that's not even valid syntactically. I tried making the generic type-parameter in the subtype to be HashMap<String, List<Thing>> and then returning new HashMap<String, List<Thing>>().getClass(), but that doesn't work because the return type of Class<T>#getClass() is Class<? extends T>. I looked at TypeToken from Guava, and the getRawType method seemed promising, but it returns Class<? super T>.

I have a workaround for the time being that looks like this:

public class ThingListMap {
    private Map<String, List<Thing>> thingListMap;

    ...
}

and I just use ThingListMap as the generic type-parameter.

Another possible workaround is to perform a forced cast:

public Class<Map<String, List<Thing>>> handledType() {
    return (Class<Map<String, List<Thing>>>) new HashMap<String, List<Thing>>().getClass();
}

Is there a more-elegant way to do this?

EDIT: In response to one of the answers, I cannot change the signature of the handledType method since I do not own or control its source.

解决方案

For some reason, Java doesn't allow you to cast Map.class directly to Class<Map<String, List<Thing>>>. It's an unchecked cast anyway.

But it's legal to cast it twice, first to Class<?>, then to Class<Map<String, List<Thing>>>.

return (Class<Map<String, List<Thing>>>) (Class<?>) Map.class;

Being an unchecked cast, you may want to add @SuppressWarnings("unchecked").

这篇关于用它的泛型类型返回一个Class实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:17