本文介绍了如何传递参数化类作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class GetMe&​​lt; T>我们的目标是开发一个可以输出指定类的对象的类。 {
public T get(){
Object obj = generateObject();
return(T)obj;


$ / code $ / pre

现在,我知道这是不可能的,因为擦除。因此,我们可以传入一个类实例并使用它来投射。

  public class GetMe&​​lt; T> {
public GetMe&​​lt; T>(Class< T> clazz){
this.clazz = clazz;


public T get(){
Object obj = generateObject();
return clazz.cast(obj);
}
}

这很棒!只要该类没有参数化。如果是这样,那么我有一个问题。



我不允许使用 List< String> .class 。如果我传递一个ParameterizedType(本身很难生成),则不需要使用 cast 方法。



有没有办法解决这个问题?

解决方案

我认为可能会为您解决此问题。


My goal is to develop a class that can output an object of a specified class.

public class GetMe<T> {
    public T get() {
        Object obj = generateObject();
        return (T) obj;
    }
}

Now, I know this isn't possible due to erasure. So, we can pass in a class instance and use that to cast.

public class GetMe<T> {
    public GetMe<T>(Class<T> clazz) {
        this.clazz = clazz;
    }

    public T get() {
        Object obj = generateObject();
        return clazz.cast(obj);
    }
}

This works great! As long as the class isn't parameterized. If it is, then I've got a problem.

I'm not allowed to use List<String>.class. If I pass in a ParameterizedType (which in itself is difficult to generate), there's no cast method to use.

Is there a way out of this quagmire?

解决方案

I think super type tokens may solve this problem for you.

这篇关于如何传递参数化类作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:59
查看更多