Question

How do I find out the name of a javascript function parsed in Java. I allow a user to type in a Javascript function (in a JTextArea), then I use ScriptEngineManager to confirm it is valid syntax as follows:

public final boolean isFunctionValid(String function)
{
    try
    {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        Object result = engine.eval(function);
    }
    catch(ScriptException se)
    {
        return false;
    }
    return true;
}

Works fine, but I also want to know the name of the function so I can assign the function a name that matches the function name. Id prefer it if ScriptEngineManager does it for me rather tham me trying to work it out by parsing the variable function with al the inherent risks of that approach

EDIT As it seems there is no way to properly do this, Ive created two checks using regular expressions that work for me.

    protected static Pattern functionNameMatch;
    protected static Pattern multipleFunctionsMatch;
    static
    {
        functionNameMatch = Pattern.compile("function[ ]+([a-zA-Z0-9]*)[ ]*\\(");
        multipleFunctionsMatch = Pattern.compile("function[ ]+");
    }


    protected boolean isOneFunction()
    {
        Matcher m = multipleFunctionsMatch.matcher(function.getText());
        if(m.find())
        {
            if(m.find())
            {
                return false;
            }
            return true;
        }
        return false;
    }

    protected String deriveNameFromFunction()
    {
        Matcher m = functionNameMatch.matcher(function.getText());
        if(m.find())
        {
            return m.group(1);
        }
        return "";
    }
Was it helpful?

Solution

So as it was not possible in JavaScript, I do some additional checks using pattern matching instead

protected static Pattern functionNameMatch;
protected static Pattern multipleFunctionsMatch;
static
{
    //TODO this method only works if all parameters are put on first line of function, otherwise declares function
    //is invalid
    functionNameMatch = Pattern.compile("function[ ]+([a-zA-Z0-9]*[ ]*\\(.*\\))");
    multipleFunctionsMatch = Pattern.compile("function[ ]+");
}

protected boolean isOneFunction()
{
    Matcher m = multipleFunctionsMatch.matcher(function.getText());
    if(m.find())
    {
        if(m.find())
        {
            return false;
        }
        return true;
    }
    return false;
}

protected String deriveNameFromFunction()
{
    Matcher m = functionNameMatch.matcher(function.getText());
    if(m.find())
    {
        return m.group(1);
    }
    return "";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top