简体   繁体   English

如何使用 Java 泛型调用带有动态参数的方法?

[英]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..我有 2 个对象,user 和 userevent ......我有 7 个通用的方法集......用户和用户事件是不同的对象,几乎没有匹配的参数......

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. User 和 UserEvent 类都将实现此接口。 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如果我理解正确,请检查我为 dao 对象编写的示例

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希望这个比喻对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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