1
我有下面的類:通Integer.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 + " ?";
}
}
下面這行編譯罰款:
Predicate<String> p1 = new Predicate<>("given_name", "=", "Kim", String.class);
但是,下列情況不:
Predicate<Integer> p1 = new Predicate<>("id", "=", "1", Integer.class);
的編譯器提到:無法推斷Predicate的類型參數<>
什麼是錯/如何解決這個問題?
有點好奇:爲什麼你在班上傳遞明確的,而不是從'operand2'參數獲取它? –
@ Mike'Pomax'Kamermans我設置了以下屬性:'private Class classType;'因爲我稍後需要它。我不知道如何從對象中提取信息。 –
Trace
你不能只使用'operand2.getClass()'? (如果它是一個int,自動裝箱會給你'整數') –