如何为参数化类型返回Class类型

时间:2017-07-10 12:40:51

标签: java

我的第一次尝试是这样的:

@Override
public Class<? extends Set<Measurement>> getType() {
    Set<Measurement> s = new HashSet<Measurement>();
    return s.getClass();
}

但它没有编译:

  

不兼容的类型:java.lang.Class java.util.Set 无法转换为java.lang.Class *?扩展java.util.Set * mydomain.Measurement **

我的第二次尝试:

@Override
public Class<? extends Set<Measurement>> getType() {
    return Set<Measurement>.class;
}

仍然无法编译:

  

无法从参数化类型中选择

2 个答案:

答案 0 :(得分:1)

好吧,你可以通过扩展通用类来做到这一点。这将允许编译器保留类型信息。

public class So45012361Application {

    public class Measurement {}

    public class MeasurementsSet extends HashSet<Measurement> {}

    public Class<? extends Set<Measurement>> getType() {
        MeasurementsSet ms = new MeasurementsSet();
        return ms.getClass();
    }

    public static void main(String[] args) {
        System.out.println(new So45012361Application().getType()); //class com.stackoverflow.So45012361Application$MeasurementsSet
        System.out.println(new So45012361Application().getType().getGenericSuperclass()); //java.util.HashSet<com.stackoverflow.So45012361Application$Measurement>
    }
}

答案 1 :(得分:0)

以下代码编译并运行:

import java.util.HashSet;
import java.util.Set;

/**
 * Created by holger on 10.07.2017.
 */
public class Sandkasten
{
    public static void main(String[] args)
    {
        new Sandkasten();
    }

    public Sandkasten()
    {
        System.out.print(getType());
    }

    public Class<? extends Set> getType() { // HERE I made some changes
        Set<String> s = new HashSet<>();
        return s.getClass();
    }
}

将输出

class java.util.HashSet