Less Verbose way of generating Play 2's javascript router

前端 未结 5 872
北海茫月
北海茫月 2021-02-06 00:54

Currently I define my app\'s javascript router in a fairly verbose way

def javascriptRoutes = Action { implicit request =>
  import routes.javascript._
  Ok(R         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-06 01:13

    I needed that in java. Copying it here in case it is of use for someone.

    public static Result javascriptRoutes() throws IllegalAccessException, IllegalArgumentException,
            InvocationTargetException {
    
        // use reflection to get the fields of controllers.routes.javascript
        Set reverseRoutes = new HashSet();
        for (Field f : controllers.routes.javascript.class.getFields()) {
            // get its methods
            for (Method m : getAllMethods(f.getType(), withReturnType(JavascriptReverseRoute.class))) {
                // for each method, add its result to the reverseRoutes
                reverseRoutes.add(m.invoke(f.get(null)));
            }
        }
    
        // return the reverse routes
        response().setContentType("text/javascript");
        return ok(Routes.javascriptRouter("jsRoutes",
                reverseRoutes.toArray(new JavascriptReverseRoute[reverseRoutes.size()])));
    }
    
        

    提交回复
    热议问题