Last active
March 10, 2025 07:56
-
-
Save MichalBrylka/699c74b0503dc3f4547600400256a710 to your computer and use it in GitHub Desktop.
Add custom function to EvalEx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package evaluation; | |
import com.ezylang.evalex.EvaluationException; | |
import com.ezylang.evalex.Expression; | |
import com.ezylang.evalex.config.ExpressionConfiguration; | |
import com.ezylang.evalex.data.EvaluationValue; | |
import com.ezylang.evalex.functions.AbstractFunction; | |
import com.ezylang.evalex.functions.FunctionParameter; | |
import com.ezylang.evalex.parser.Token; | |
import lombok.extern.slf4j.Slf4j; | |
import java.util.*; | |
@FunctionParameter(name = "value", isVarArg = true) | |
class IsNumberFunction extends AbstractFunction { | |
public static final String NAME = "IS_NUMBER"; | |
@Override | |
public EvaluationValue evaluate(Expression expression, Token functionToken, EvaluationValue... parameterValues) throws EvaluationException { | |
if (parameterValues.length != 1) | |
throw new EvaluationException(functionToken, "%s requires exactly one parameter.".formatted(NAME)); | |
try { | |
Double.parseDouble(parameterValues[0].getStringValue()); | |
return EvaluationValue.booleanValue(true); | |
} catch (NumberFormatException e) { | |
return EvaluationValue.booleanValue(false); | |
} | |
} | |
} | |
@Slf4j | |
public class Main { | |
@lombok.SneakyThrows | |
public static void main(String[] args) { | |
var configuration = ExpressionConfiguration.builder() | |
//.mathContext() | |
.build() | |
.withAdditionalFunctions( | |
Map.entry(IsNumberFunction.NAME, new IsNumberFunction()) | |
); | |
Expression expression = new Expression("IF(IS_NUMBER(value), value < 5.0, NULL)", configuration) | |
.with("value", 5.0) | |
//.with("value", "ATMF") | |
; | |
EvaluationValue result = expression.evaluate(); | |
System.out.println(result.getBooleanValue()); | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<dependency> | |
<groupId>com.ezylang</groupId> | |
<artifactId>EvalEx</artifactId> | |
<version>3.4.0</version> | |
</dependency> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment