Reputation: 141
I have below class created.
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
}
}
In above class Employee
, Billing
and Level
are Java POJOs.
Now how can i instantiate above SomeRequest
class?
Thanks!
Upvotes: 0
Views: 67
Reputation: 246
In Java 5 or 6 you can use factory method as replacement for constructor with generics. In Java 5 or 6 type inference work fine on methods but not on constructors. You can write something like:
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);
}
}
Now you should't write new SomeRequest(billing, employee, level)
, you can write simple SomeRequest.with(billing, employee, level)
.
Oh, sorry, I asked before have seen your comment about Java 7.
Upvotes: 0
Reputation: 246
@user3269829 you should not use HashMap for contain data of different types. You can add custom container, i.e. a class with three field:
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!
}
The process() method will have next signature:
public void process(Container<B, E, L> input)
In the process() method you can:
SomeRequest<Billing,Employee,Level> instance = new SomeRequest<>();
instance.setBilling(container.getBilling());
instance.setEmployee(container.getEmployee());
instance.setLevel(container.getLevel());
or
SomeRequest<Billing,Employee,Level> instance = new SomeRequest<>(container.getBilling(), container.getEmployee(), container.getLevel());
Upvotes: 0
Reputation: 41935
Assuming that SomeRequest
class has a no-arg constructor
In Java 7 using the diamond operator
SomeRequest<Billing,Employee,Level> instance = new SomeRequest<>();
In Java 6 or 5
SomeRequest<Billing,Employee,Level> instance = new SomeRequest<Billing,Employee,Level>();
Upvotes: 1