通用地图参数Java [英] Generic Map Parameter java

查看:55
本文介绍了通用地图参数Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多这种类型的方法:

I am having a lot of methods of this type:

public static List<EduUsers> getDetails(Class c, Map<String, Integer> params) {
        List<EduUsers> details = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Criteria cr = session.createCriteria(c);
            for (Map.Entry<String, Integer> entry : params.entrySet()) {
                cr.add(Restrictions.eq(entry.getKey(), entry.getValue()));
            }
            details = cr.list();
            tx.commit();
        } catch (Exception asd) {
            log.debug(asd.getMessage());
            if (tx != null) {
                tx.commit();
            }
        } finally {
            session.close();
        }
        return details;
    }

我正在尝试为他们准备一个通用方法,这是我到目前为止编写的内容:

I am trying to have a generic Method for them and this is what I have written so far:

 public static <T> List<T> getDetails(Class<T> c, Class<T> b) {
        List<T> details = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Criteria cr = session.createCriteria(c);
            //am stuck on iteration of the map from Class T b
            details = cr.list();
            tx.commit();
        } catch (Exception asd) {
            log.debug(asd.getMessage());
            if (tx != null) {
                tx.rollback();
            }
        } finally {
            session.close();
        }
        return details;
    }

如何在方法上放置通用Map?

How do I put up a generic Map onto the method?

我的地图值类型可以更改,我不仅需要放置整数,还需要放置字符串以及其他类型

推荐答案

要使用通用地图,您应定义方法,以允许带有任何类型对象的地图传递 Value 地图的位置.

To use generic map you should define your method to allow a Map with any type of object to pass in Value place of Map.

您的新方法应如下所示: getDetails(Class< T> c,Map< String,?>参数)

Your new method should look like this getDetails(Class<T> c,Map<String,?> params)

和Map Entry迭代器应如下图所示:

and Map Entry iterator should look like as below:

for (Map.Entry<String, Object> entry : params.entrySet()) {
                cr.add(Restrictions.eq(entry.getKey(), entry.getValue()));
 }

这篇关于通用地图参数Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆