Java中是否存在这些比较运算符(<,< =,==,> =,>,!=)的对象表示?
E.g。用例:
void filterHotel( Object operator, float rating ) {
String query = "SELECT hotel.name from hotel where hotel.rating " +
operator.toString() + rating;
// execute query
}
答案 0 :(得分:3)
否即可。但是编写起来很容易,考虑将enum
与自定义方法一起使用:
public enum Operator {
EQUAL("=="),
NOT_EQUAL("<>"),
GREATER_THAN(">"),
GREATER_THAN_OR_EQUAL(">="),
LESS_THAN("<"),
LESS_THAN_OR_EQUAL("<=");
private final String representation;
private Operator(String representation) {
this.representation = representation;
}
public String getRepresentation() {
return representation;
}
}
通过,例如Operator.LESS_THAN
并使用operator.getRepresentation()
提取实际运算符。
另外,请确保用户不能使用任意字符串代替operator
以避免sql-injection。
答案 1 :(得分:1)
内置任何内容,但您可以定义一个enum
来实现这一目的:
public enum ComparisonOperator {
LT("<"), LE("<="), EQ("=="), NE("<>"), GE(">="), GT(">");
ComparisonOperator(String symbol) { this.symbol = symbol; }
private final String symbol;
public String toSymbol() { return symbol; }
}
然后:
void filterHotel(ComparisonOperator operator, float rating) {
String query = "SELECT hotel.name from hotel where hotel.rating " +
operator.toSymbol() + rating;
// execute query
}