Normally I exercise this when I receive got a method inwards a base of operations class that returns a generic type. For example:
public class Parent<E extends BaseType> { populace east e; populace east getType() { supply e; } } populace class Childextends Parent { populace Child() { super(Type.class); } } populace class Type extends BaseType { }
The instance doesn't brand feel inwards delineate of piece of work concern exactly if you lot volition expect at it equally a slice of code you lot tin reckon that you lot tin kicking the bucket the dynamic type specified inwards Child inwards Parent class.
Now a to a greater extent than logical instance :-) Assume that receive got the following:
entity User, Role;
service: UserService, RoleService
bean: UserBean, RoleBean
Often nosotros create a CRUD for these types of entities as well as and thence nosotros involve dynamic page generation as well as extendable entity, edible bean as well as service. That volition create mutual things similar for instance inwards service: find, create, delete, update.
Let's start amongst the entity User as well as Role, both of them should extend a BaseEntity. I'll omit the notation since I'm lame :-).
public interface IEntity { populace Long getId(); } populace class BaseEntity implements Serializable, IEntity { someone Long id; } populace class User extends BaseEntity { someone String username; } populace class Role extends BaseEntity { someone String roleName; }Now latterly I encountered a occupation where I desire to parameterized the entity as well as service inwards a baseBean. So I starting fourth dimension configure the base of operations service:
public interfaces IPersistenceService { populace void create(); populace void remove(); //... } populace abstract class PersistenceService<E extends IEntity> implements IPersistenceService<E> { populace void create() { //.. } populace void remove() { //.. } } //Why extends? because whether the IEntity is a class or interface, east e'er extends it.Now the much complicated part, how create I top the entity as well as service dynamically to a base of operations bean?
public class BaseBean<E extends IEntity, T extends PersistenceService<E>> { someone east entity; @Inject someone T persistenceService; populace void create() { persistenceService.create(); } } populace class UserBean<User, UserService> extends BaseBean { populace UserBean() { super(User.class, UserService.class); } } populace class RoleBean<User, RoleService> extends BaseBean { populace RoleBean() { super(Role.class, RoleService.class); } }Also receive got banking concern complaint that I was successful inwards injecting a generic service :-).
Now what if I receive got an unknown activity as well as I desire to kicking the bucket the BaseBean amongst the right type? Here's how I did it:
public BaseBean<? extends IEntity, ? extends PersistenceService<?>> getBaseBean() { supply null; }
0 komentar:
Please comment if there are any that need to be asked.