[英]Generic Map Parameter 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;
}
How do I put up a generic Map onto the method? 如何在方法上放置通用Map?
EDIT: My Map values type can change I need to be able to put not just Integers but Strings as well and other types 编辑:我的地图值类型可以更改,我不仅需要放置整数,还需要放置字符串以及其他类型
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 . 要使用通用的地图,你应该定义你的方法,以便与任何类型的对象的地图在地图的价值的地方通过。
Your new method should look like this getDetails(Class<T> c,Map<String,?> params)
您的新方法应类似于以下
getDetails(Class<T> c,Map<String,?> params)
and Map Entry iterator should look like as below: 和Map Entry迭代器应如下所示:
for (Map.Entry<String, Object> entry : params.entrySet()) {
cr.add(Restrictions.eq(entry.getKey(), entry.getValue()));
}
Just as easy as adding Map<? extends Object, ? extends Object>
就像添加
Map<? extends Object, ? extends Object>
一样容易Map<? extends Object, ? extends Object>
Map<? extends Object, ? extends Object>
Map<? extends Object, ? extends Object>
to your method's parameters list. Map<? extends Object, ? extends Object>
到方法的参数列表。
public static<T> List<T> getDetails(Class<T> c, Map<? extends Object, ? extends Object> params)
Another option would be adding two other parameter types: 另一种选择是添加其他两个参数类型:
private static <T, S, X> List<T> getDetails(Class<T> clazz, Map<S, X> map) {
...
for (Map.Entry<S, X> entry : params.entrySet()) {
cr.add(Restrictions.eq(entry.getKey(), entry.getValue()));
}
...
}
The new parameter Class<T> b
can be removed, since it doesn't been used anywhere. 可以删除新参数
Class<T> b
,因为它没有在任何地方使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.