Skip to content

Instantly share code, notes, and snippets.

@na-ka-na
Created April 12, 2011 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save na-ka-na/915683 to your computer and use it in GitHub Desktop.
Save na-ka-na/915683 to your computer and use it in GitHub Desktop.
Power of Reflection + Enum + Comparable to generate a simple expression evaluator
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class AProp implements Comparable<AProp>{
private final int a;
public AProp(int a){
this.a = a;
}
@Override
public int compareTo(AProp other) {
return ((Integer) a).compareTo(other.a);
}
}
class AnAggregate{
private final AProp a;
public AnAggregate(AProp a){
this.a = a;
}
public AProp getAProp(){ return a; }
}
enum OP{
EQ, NE, GTE, LTE, LT, GT;
}
class SimpleExpression<E>{
private final OP op;
private final Method lhs_m;
private final E rhs;
public SimpleExpression(OP op, Method lhs_m, E rhs) {
this.op = op;
this.lhs_m = lhs_m;
this.rhs = rhs;
}
public boolean eval(AnAggregate lm) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Comparable<E> lhs = (Comparable<E>) lhs_m.invoke(lm);
switch (op) {
case EQ:
return lhs.compareTo(rhs) == 0;
case NE:
return lhs.compareTo(rhs) != 0;
case GTE:
return lhs.compareTo(rhs) >= 0;
case LTE:
return lhs.compareTo(rhs) <= 0;
case GT:
return lhs.compareTo(rhs) > 0;
case LT:
return lhs.compareTo(rhs) < 0;
}
return false;
}
}
class SimpleExpressionCreator{
private final Method getAProp;
public SimpleExpressionCreator() throws SecurityException, NoSuchMethodException{
getAProp = AnAggregate.class.getMethod("getAProp");
}
public SimpleExpression<AProp> aPropCompare(OP op, AProp rhs){
return new SimpleExpression<AProp>(op, getAProp, rhs);
}
}
public class ExprEval{
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
AnAggregate lm = new AnAggregate(new AProp(200));
SimpleExpressionCreator sec = new SimpleExpressionCreator();
SimpleExpression<AProp> se;
se = sec.aPropCompare(OP.EQ, new AProp(100));
System.out.println(se.eval(lm));
se = sec.aPropCompare(OP.LT, new AProp(100));
System.out.println(se.eval(lm));
se = sec.aPropCompare(OP.GT, new AProp(100));
System.out.println(se.eval(lm));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment