Search in sources :

Example 1 with ImportScope

use of com.googlecode.aviator.annotation.ImportScope in project aviatorscript by killme2008.

the class AviatorEvaluatorInstance method importFunctions.

/**
 * Import the class public methods into aviator evaluator as custom functions. The function's
 * namespace is the class name by default, and the scopes are both static and instance methods.
 * The namespace and scope can be set by {@link Import} annotation.
 *
 * @since 4.2.2
 * @see Import
 * @param clazz the class
 * @return the added function list.
 * @throws NoSuchMethodException
 * @throws IllegalAccessException
 */
public List<String> importFunctions(final Class<?> clazz) throws IllegalAccessException, NoSuchMethodException {
    String namespace = clazz.getSimpleName();
    ImportScope[] scopes = { ImportScope.Static, ImportScope.Instance };
    Import importAnt = clazz.getAnnotation(Import.class);
    if (importAnt != null) {
        namespace = importAnt.ns();
        if (namespace == null || namespace.isEmpty() || !ExpressionParser.isJavaIdentifier(namespace)) {
            throw new IllegalArgumentException("Invalid namespace in Import annotation: " + namespace);
        }
        scopes = importAnt.scopes();
        if (scopes == null || scopes.length == 0) {
            throw new IllegalArgumentException("Empty scopes in Import annotation");
        }
    }
    List<String> result = new ArrayList<>();
    for (ImportScope scope : scopes) {
        switch(scope) {
            case Static:
                result.addAll(addStaticFunctions(namespace, clazz));
                break;
            case Instance:
                result.addAll(addInstanceFunctions(namespace, clazz));
                break;
            default:
                throw new IllegalStateException("Invalid import scope: " + scope);
        }
    }
    return result;
}
Also used : Import(com.googlecode.aviator.annotation.Import) ImportScope(com.googlecode.aviator.annotation.ImportScope) ArrayList(java.util.ArrayList)

Aggregations

Import (com.googlecode.aviator.annotation.Import)1 ImportScope (com.googlecode.aviator.annotation.ImportScope)1 ArrayList (java.util.ArrayList)1