大家帮忙看下这段代码什么意思.
我知道下面那个是取得条件和取得记录.可是调用中间那段代码.应该是用到了反射.不知道怎么运行的.请帮忙解释下.谢谢了.
public static Collection getByCondition(String hql,Class cls,Object queryObj,
int fromNum, int pageShowNum) {
Collection col = new ArrayList();
Session s = null;
Transaction t = null;

try{
s = SFUtil.getSF().openSession();//取得session
t = s.beginTransaction();
Query q = s.createQuery(hql);

invokeSetValue(cls,q,queryObj);

q.setFirstResult(fromNum);
q.setMaxResults(pageShowNum);

col = q.list();

t.commit();
}catch(Exception err){
t.rollback();
err.printStackTrace();
return null;
}finally{
s.close();
}
return col;
}
private static void invokeSetValue(Class cls,Query q,Object queryObj) throws Exception{
Class partypes[] = new Class[2];
partypes[0] = Query.class;
partypes[1] = Object.class;
Method meth = cls.getMethod("setValue", partypes);
Object argCollection[] = new Object[2];
argCollection[0] = q;
argCollection[1] = queryObj;
Object retobj = meth.invoke(cls, argCollection);
}

public static long getCount(String hql,Class cls,Object queryObj){
long count = 0;
Session s = null;
Transaction t = null;
try{
s = SFUtil.getSF().openSession();
t = s.beginTransaction();
Query q = s.createQuery(hql);
if(queryObj!=null){
invokeSetValue(cls,q,queryObj);
}
count=(Long) q.list().get(0);

t.commit();
}catch(Exception err){
t.rollback();
err.printStackTrace();
return count;
}finally{
s.close();
}
return count;
}

解决方案 »

  1.   

    private static void invokeSetValue(Class cls,Query q,Object queryObj)你是不是说这个方法里面的代码看不懂
      

  2.   

    嗯.对.这个方法看不太懂.具体做了哪些事情.比如new了什么东西.返回的是什么.我反射机制看了一会文档还是看不懂.
      

  3.   

     Class partypes[] = new Class[2];
            partypes[0] = Query.class;//加载对象
            partypes[1] = Object.class;
            Method meth = cls.getMethod("setValue", partypes);//获取对象的setvalue方法
            Object argCollection[] = new Object[2];
            argCollection[0] = q;
            argCollection[1] = queryObj;
            Object retobj = meth.invoke(cls, argCollection);//调用方法看api
      

  4.   

    这个很简单啊!Class partypes[] = new Class[2]; 
            partypes[0] = Query.class;
              partypes[1] = Object.class; 
            Method meth = cls.getMethod("setValue", partypes);
    //获取对象的setValue方法,这个方法带两个参数,
    一个是 Query类型,一个是Object类型,就是定义的partypes数组。
    其实这个方法是这样 的:setValue(Query q,Object queryObj)
            Object argCollection[] = new Object[2]; 
            argCollection[0] = q; 
            argCollection[1] = queryObj; 
            Object retobj = meth.invoke(cls, argCollection);//调用setValue方法,传入实参,
    其实是这样的:setValue(q,queryObj)
      

  5.   

    用反射调用了一个静态的方法"setValue",你没有帖出来。我猜那个方法做的工作大概就是queryObj里面的值get出来然后set到query里面去,作为查询条件。纯靠猜的,或者你把那个方法先帖出来看看吧 我也好奇为什么要把这个方法写在多个class里面,想看看
      

  6.   

     Object retobj = meth.invoke(cls, argCollection);
    就是典型的反射。
    用Method对象来为cls设置值.
      

  7.   

    哦.这个setValue是struts2标签库自带的.明白了.谢谢大家.