Are there any object representation of these comparison operators (<, <=, ==, >=, >, !=) in Java ?
Eg use case:
void filterHotel( Object operator, float rating ) {
String query = "SELECT hotel.name from hotel where hotel.rating " +
operator.toString() + rating;
// execute query
}
No . But it is easy to write, consider using enum
with custom method:
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;
}
}
Pass eg Operator.LESS_THAN
and extract actual operator using operator.getRepresentation()
.
Also make sure user cannot put arbitrary string in place of operator
to avoid sql-injection .
There's nothing built in, but you can define an enum
that does the trick:
public enum ComparisonOperator {
LT("<"), LE("<="), EQ("=="), NE("<>"), GE(">="), GT(">");
ComparisonOperator(String symbol) { this.symbol = symbol; }
private final String symbol;
public String toSymbol() { return symbol; }
}
Then:
void filterHotel(ComparisonOperator operator, float rating) {
String query = "SELECT hotel.name from hotel where hotel.rating " +
operator.toSymbol() + rating;
// execute query
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.