2

如何用 PathBuilder 替换以下使用生成的 Q* 类和 java 反射的方法?

// member vars:
T operand;  // can be a BigDecimal or a String
String tableName;
String fieldName;
String methodName;

public Predicate asPredicate()
{
   Class<?> tableClazz = Class.forName("foo.bar.database.model.Q"+ WordUtils.capitalize(tableName));
   Object tableObj = tableClazz.getConstructor(String.class).newInstance(tableName +"1000");
   Field colField = tableClazz.getDeclaredField(fieldName);
   Object colObj = colField.get(tableObj);

   Class classParam = Object.class;
   if(methodName.matches(".*like"){
     classParam = String.class;
   }
   // method name is one of eq, ne, like...
   Method m = colObj.getClass().getMethod(methodName, classParam );
   return (Predicate) m.invoke(colObj, operand);
}

这很好用,但我被建议使用 PathBuilder 来回答我的其他问题https://stackoverflow.com/questions/15269845/querydsl-extract-table-name-from-predicate-booleanexpression-object)这也将删除尴尬的 newInstance(tableName +"1000")。

PathBuilder<?> entityPath = new PathBuilder("foo.bar.database.model.Q"+ WordUtils.capitalize(tableName), "entity"); // what does the second param stand for?
PathBuilder relation = entityPath.get(fieldName);
// ???

两个问题:1)我现在可以在关系上调用 eq() 或 ne(),但不能调用 like()、notLike() 2) 如何获取 colObj 以便可以使用 java 反射 colObj.getClass().getMethod(. ..)

解决方案: 感谢 Timo 的回答,除了两个 instanceof 条件外,我完全放弃了反射,现在使用此代码:

tableClazz = Class.forName("foo.bar.database.model."+ WordUtils.capitalize(tableName));
PathBuilder<?> entityPath = new PathBuilder(tableClazz, tableName +"1000");
Predicate predicate = null;

if(operand instanceof String){
   StringPath path = entityPath.getString(fieldName);
   switch(type){
       case EQ:
          predicate = path.eq((String) operand);
       case CONTAINS:
          predicate = path.like("%" + operand +"%");
          break;
      // snip BEGINS WITH, ENDS WITH
    }
}else if(operand instanceof BigDecimal){
    assert(type.equals(Type.EQ));
    NumberPath<BigDecimal> path = entityPath.getNumber(fieldName, BigDecimal.class);
    predicate = path.eq((BigDecimal) operand);
}
if(negation){
  return predicate.not();
}
return predicate;
4

1 回答 1

7

你应该像这样使用它

// entityClass is the entity type, not the Q-type
Class<?> entityClass = Class.forName(...)
// "entity" is the variable name of the path
PathBuilder<?> entityPath = new PathBuilder(entityClass, "entity"); 
// use getString to get a String path
Predicate predicate = entityPath.getString("property").like("a%");
于 2013-03-07T14:28:40.860 回答