简体   繁体   中英

How to use Java generics for calling method with dynamic parameter?

I have 2 objects, user and userevent... And I have set of 7 methods common for both.. User and userevent are different objects with few matching parameters..

How to implement this with generics so that I can reuse the methods for both user and userevents ?? Method accept user or userevent or both object as parameter..

Why not use an interface?

Both User and UserEvent classes would implement this interface. Common methods would be declared in the Interface and overriden in both classes. As for the methods, they would accept as parameters any object that implements the newly created Interface.

If I understood you correctly, kindly check my example written for dao object

public interface IDao<T> {
void saveOrUpdate(T instance);

Long save(T instance);

void delete(T instance);

T get(Long id);
}

public class BasicHibernateDao<T> extends HibernateDaoSupport implements IDao<T> {
private final Class<T> clazz;

public BasicHibernateDao(Class<T> clazz) {
    this.clazz = clazz;
}

public void saveOrUpdate(T instance) {
    getHibernateTemplate().saveOrUpdate(instance);
}

public Long save(T instance) {
    return (Long) getHibernateTemplate().save(instance);
}

public void delete(T instance) {
    getHibernateTemplate().delete(instance);
}

public T get(Long id) {
    return getHibernateTemplate().get(clazz, id);
}
}

public class ClientDao extends BasicHibernateDao<Client> {

public ClientDao() {
    super(Client.class);
}
}

Hope that this analogy would be helpful for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM