Java 中是否有这些比较运算符(<、<=、==、>=、>、!=)的对象表示形式?
例如使用案例:
void filterHotel( Object operator, float rating ) {
String query = "SELECT hotel.name from hotel where hotel.rating " +
operator.toString() + rating;
// execute query
}
最佳答案
不。但它很容易编写,考虑使用 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()
提取实际运算符。
还要确保用户不能用任意字符串代替运算符
以避免sql-injection .
关于java - java中的比较运算符对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9671865/