3

CriteriaBuilder has overloaded method isMember(...)

Create a predicate that tests whether an element is a member of a collection.

<E,C extends java.util.Collection<E>> 
Predicate isMember(E elem, Expression<C> collection) 

<E,C extends java.util.Collection<E>> 
Predicate isMember(Expression<E> elem, Expression<C> collection) 

I got ambiguous compilation error for the following call:

CriteriaBuilder.isMember((Expression<Object>)a, (Expression<Collection<Object>>)b);

The member type can be any, so it is Object type. How to fix it? Thanks.

Dave
  • 759
  • 2
  • 9
  • 31

2 Answers2

2

You can declare an (unchecked) generic type to link the casts, perhaps in an internal private method to avoid it being visible to other callers. This even compiles:

CriteriaBuilder cb;
Object a;
Object b;

@SuppressWarnings("unchecked")
private <E> void isMember() {

    cb.isMember((Expression<E>) a, (Expression<? extends Collection<E>>) b);
}

Though a and b would be better as type Expression, and/or as local variables or parameters in the method for more local scoping.

df778899
  • 10,703
  • 1
  • 24
  • 36
0

The problem for the compiler is that (Expression<Object>)a may also be of actual Type E which is just Object. In order to get the Method running you have to avoid the cast.

You can find a good example why this error occurs in this enter link description here.

ata
  • 3,398
  • 5
  • 20
  • 31
JoeJoesen
  • 61
  • 7
  • avoiding the cast don't help if the data structure should be so generic. i have this case and i guess the OP has the same kind of issue. – snap Jun 04 '18 at 13:43