Evaluating javascript using a java code

后端 未结 3 878
我寻月下人不归
我寻月下人不归 2021-01-05 19:23

This might not be practical, but I have it as a task. I have an opened ServerSocket in java. Now I want to read a file which contains html and javascript, and output the jav

3条回答
  •  天命终不由人
    2021-01-05 20:10

    public static String convertEnumToJson(Class> cls) throws ScriptException, NoSuchMethodException, IllegalAccessException {
        List> map = createMap(Colors.class);
        return createJson(map);
    }
    
    public static List> createMap(Class> cls) throws IllegalAccessException {
        List> res = new ArrayList<>();
    
        for (Enum item : cls.getEnumConstants()) {
            Map map = new LinkedHashMap<>();
    
            for (Field field : item.getClass().getDeclaredFields()) {
                if (field.getType() != item.getClass() && !"$VALUES".equals(field.getName())) {
                    field.setAccessible(true);
                    map.put(field.getName(), field.get(item));
                }
            }
    
            res.add(map);
        }
    
        return res;
    }
    
    // It's better to use Jackson or similar lib for read/write json
    public static  String createJson(T obj) throws ScriptException, NoSuchMethodException {
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        engine.eval("function sum(a){ return a;}");
        return ((Invocable)engine).invokeFunction("sum", obj).toString();
    }
    

提交回复
热议问题