根据泛型加入

Join depending on generic type

我的 RefineByBasicTaskType 应该为不同的 CriteriaQuery 类型添加相同的条件。 T 可以是任务或约会。唯一的区别是,如果 T 是任务,则不需要连接。

如何将我的 RefineByBasicTaskType class 用于多个类型?

public class RefineByBasicTaskType<T> extends AbstractRefinement<T> {

private BasicTaskType basicTaskType;

public Predicate addCriteriaQuery(CriteriaQuery<T> criteria, CriteriaBuilder builder, Root<T> taskRoot) {
    
    if (T instanceof Task) {
        return refineByBasicTaskType(builder,
                                     taskRoot);
    }

    return refineByBasicTaskType(builder,
                                 fetchOrCreateFirstJoin(taskRoot,"task"));
}...

从正确的面向对象的角度来看,您正在尝试重新发明已经可以通过继承实现的机制:

public abstract class RefineByBasicTaskType<T> extends AbstractRefinement<T> {

  public abstract Predicate addCriteriaQuery(CriteriaQuery<T> criteria, CriteriaBuilder builder, Root<T> root);
}
public class RefineByTask extends RefineByBasicTaskType<Task> {
  
  @Override
  public Predicate addCriteriaQuery(CriteriaQuery<Task> criteria, CriteriaBuilder builder, Root<Task> root) {
    return refineByBasicTaskType(builder, root);
  }
}
public class RefineByWhatever extends RefineByBasicTaskType<Whatever> {
  
  @Override
  public Predicate addCriteriaQuery(CriteriaQuery<Whatever> criteria, CriteriaBuilder builder, Root<Whatever> root) {
    return refineByBasicTaskType(builder, fetchOrCreateFirstJoin(root, "task"));
  }
}

编辑:如果您不想使用继承,您应该能够从 Root 对象中获取 Java 类型,这样您也可以替换您的 if-statement与:

if (taskRoot.getJavaType().equals(Task.class)) {
  // ...
}