我有以下课程:
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 + " ?";
}
}
以下行编译正常:
Predicate<String> p1 = new Predicate<>("given_name", "=", "Kim", String.class);
但是,以下情况并非如此:
Predicate<Integer> p1 = new Predicate<>("id", "=", "1", Integer.class);
编译器提到:无法推断Predicate&lt;&gt;
的类型参数有什么问题/如何解决这个问题?
答案 0 :(得分:7)
“1”是一个字符串,与Integer.class
不兼容new Predicate<>("id", "=", 1, Integer.class)
应该没问题
或
new Predicate<>("id", "=", "1", String.class)