问题
I have needed in several occasions some classes to represent and manipulate conditions (typically in a UI so the user builds a query by combining different condition types and then the code can transform that depending on the underlying system to be queried, for example lucene and a db). I searched all over for a reusable set of classes, I am sure this has to be used in many existing places (all the expression languages for starters) but could not find anything easily usable. I ended up coding both times myself, but felt bad about not reusing something I am sure exists.
Typical needs are: - several operators: and or etc - variable number of operands - combining conditions to build expressions - serializing of expressions - parsing/formatting of expressions from/to strings
has somebody found something like that?
回答1:
Take a look at Apache Commons Functor. E.g. UnaryPredicate, UnaryAnd, UnaryOr, etc. The built-in implementations are Serializable, but I don't know about parsing from strings. Still, I think it's a very good start towards what you want. Also, take a look at this IBM tutorial based on the library.
回答2:
It does sound like you might be looking for Functors (aka function objects). If so, this SO question would be relevant, wrt. choices: Commons functor (mentioned already) is one alternative but there are others too.
All functor libs come with the framework (which is quite simple; unary, binary predicates, mapping functionality for those, combining by chaining) and basic set of functions most commonly needed.
回答3:
This sounds like you are looking for something like the Hibernate Criteria API. The drawback is that you are tied to a database or even worse a specific persistence framework implementation. Also it does not cover all of you requirements, so I do not think this is a good choice then...
回答4:
You may want to check out ANTLR.
来源:https://stackoverflow.com/questions/833754/reusable-condition-expression-classes