如何实例化泛型类

时间:2013-05-13 17:18:03

标签: java

我以为我明白了如何使用.classClass<>,但我猜不是。以下super(ApprovalWorkstation.class未映射到构造函数。我怎样才能确定我传递了一个类引用,以便基类WorkstationRequest可以实例化它?

public class ApprovalWorkstation extends Workstation {

    public ApprovalWorkstation(WorkstationEntity entity) {
        super(entity);
    }
}

public class WorkstationRequest extends com.production.socket.request.WorkstationRequest {
    public WorkstationRequest() {
        super(ApprovalWorkstation.class); //unable to map to constructor
    }
}

这是扩展到

以上的基础WorkstationRequest
public class WorkstationRequest {
    private Class<Workstation> workstationClass;

    public void WorkstationRequest(Class<Workstation> workstationClass) {
        this.workstationClass = workstationClass;
    }

更新

我很抱歉这个混乱,我的构造函数实际上有Class<Workstation>而不是Workstation,正如我最初的那样。

4 个答案:

答案 0 :(得分:4)

为了能够传递Workstation类及其子类,您应该将WorkstationRequest的定义更改为以下内容:

public class WorkstationRequest {
    private Class<? extends Workstation> workstationClass;

    public WorkstationRequest(Class<? extends Workstation> workstationClass) {
        this.workstationClass = workstationClass;
    }
}

答案 1 :(得分:0)

如果我错了,请纠正我,但是你传递Workstation个实例,而需要的是Class<Workstation>。也许使用workstationClass.getClass()代替?

答案 2 :(得分:0)

您尝试将Worstation的实例分配给Class<Workstation>类型的字段,这显然不相同。

你可能要做的是:

public WorkstationRequest(Class<Workstation> workstationClass) {

当然,构造函数中没有返回类型(void)。你的“构造函数”只是一种方法:

public void WorkstationRequest(Class<Workstation> workstationClass) { // method
public      WorkstationRequest(Class<Workstation> workstationClass) { // constructor

答案 3 :(得分:0)

  1. 没有构造函数在基础WorkstationRequest类中将Class作为参数。
  2. 构造函数没有返回类型,因此public void WorkstationRequest需要更改为public WorkstationRequest