实例化具有通用参数的类?

时间:2014-02-14 07:47:12

标签: java generics

我在下面创建了类。

public class SomeRequest<B extends Billing,E extends Employee, L extends Level>{


B billing;


E employee;

Class<L> level;

public void process(HashMap<String, Object> input){

        this.billing = (B)data.get("billing");
    this.employee= (E)data.get("employee");
    this.level = (Class<L>)data.get("level");

         //Some logic

  }

}

在上面的课程Employee中,BillingLevel是Java POJO。

现在我如何实例化以上SomeRequest类?

谢谢!

3 个答案:

答案 0 :(得分:1)

假设SomeRequest类有一个无参数构造函数

在Java 7中使用diamond operator

SomeRequest<Billing,Employee,Level> instance = new SomeRequest<>();

在Java 6或5中

SomeRequest<Billing,Employee,Level> instance = new SomeRequest<Billing,Employee,Level>();

答案 1 :(得分:0)

在Java 5或6中,您可以使用工厂方法替换具有泛型的构造函数。在Java 5或6中,类型推断在方法上工作得很好,但在构造函数上却没有。你可以这样写:

public class SomeRequest<B extends Billing,E extends Employee, L extends Level>{
   private SomeRequest(B billing, E employee, L level) {
       // ...
   }

   public static <B,E,L> with(B billing, E employee, L level) {
        return new SomeRequest<B, E, L>(billing, employee, level);
   }
}

现在你不应该写new SomeRequest(billing, employee, level),你可以写简单的SomeRequest.with(billing, employee, level)

哦,对不起,我之前已经看过你对Java 7的评论。

答案 2 :(得分:0)

@ user3269829您不应该使用HashMap来包含不同类型的数据。您可以添加自定义容器,即具有三个字段的类:

class Container<B extends Billing,E extends Employee, L extends Level> {

    B billing;

    E employee;

    L level;

    public Container(B b, E e, L l) {
        billing = b;
        employee = e;
        level = l;
    }

    // ... getters only!
}

process()方法将具有下一个签名:

 public void process(Container<B, E, L> input)

在process()方法中,你可以:

SomeRequest<Billing,Employee,Level> instance = new SomeRequest<>();
instance.setBilling(container.getBilling());
instance.setEmployee(container.getEmployee());
instance.setLevel(container.getLevel());

SomeRequest<Billing,Employee,Level> instance = new SomeRequest<>(container.getBilling(), container.getEmployee(), container.getLevel());
相关问题