1

I have the following class:

package query;

public class Predicate<T> {

    private String operand1; 
    private String operator; 
    private T operand2; 
    private Class<T> classType; 

    public Predicate(String operand1, T operand2, Class<T> classType){
        this(operand1, "=", operand2, classType); 
    }

    public Predicate(String operand1, String operator, T operand2, Class<T> classType){
        this.operand1 = operand1; 
        this.operator = operator; 
        this.operand2 = operand2; 
        this.classType = classType; 
    }

    public String getOperand1() {
        return operand1;
    }

    public String getOperator() {
        return operator;
    }

    public T getOperand2() {
        return operand2;
    }

    public Class<T> getClassType() {
        return classType;
    }

    @Override
    public String toString() {
        return operand1 + " " + operator + " ?"; 
    }
}

The following line compiles fine:

Predicate<String> p1 = new Predicate<>("given_name", "=", "Kim", String.class); 

However, the following does not:

Predicate<Integer> p1 = new Predicate<>("id", "=", "1", Integer.class); 

The compiler mentions: Cannot infer type arguments for Predicate<>

What is wrong / how can solve this?

8
  • A little curious: why are you passing in the class explicitly instead of getting it from the operand2 argument? Commented Jan 24, 2016 at 18:26
  • @Mike'Pomax'Kamermans I set the following property: private Class<T> classType; because I need it later on. I'm not sure how to extract the information from the object. Commented Jan 24, 2016 at 18:39
  • can't you just use operand2.getClass()? (if it's an int, autoboxing will give you Integer) Commented Jan 24, 2016 at 18:48
  • I tried it, but the compiler requests an explicit cast. The problem is that if I do, I get a warning that I'm dealing with an unchecked cast. But the invocation is cleaner, isn't it? Perhaps I should go with this. Commented Jan 24, 2016 at 18:56
  • what about a getClass, check for identity on T, if it checks out, you can safely cast. Commented Jan 24, 2016 at 19:07

1 Answer 1

7

"1" is a String and incompatible with Integer.class

new Predicate<>("id", "=", 1, Integer.class)

should be ok

or

new Predicate<>("id", "=", "1", String.class)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.