Search code examples
javajavascriptscriptingenumsrhino

Exposing Java Enums in the Rhino JavaScript engine


I'm writing a program that incorporates the Rhino Scripting Engine. I would like to be ale to expose a couple of the program's enums, but I can't figure out how to do that, if it's even possible. Is there a way to make a java enum usable in the scripts?


Solution

  • Do you mean to use a java Enum from a script, which will be converted to Java by Rhino?. If this is the case, you could do something like:

    • given a java class with an Enum:

      package com.stackoverflow.example;
      public class Order {
      
          private String field;
          private By by;
      
          public enum By {
              ASC, DESC
          }
      
          public Order(String field, By by) {
              this.field = field;
              this.by = by;
          }
      }
      
    • and in the script you can do

      // Importing class with enum
      importClass(Packages.com.stackoverflow.example.Order);
      
      // Instancing a new Order object using the existing enum in the Order class
      var order = new Order("db_field", Order.By.DESC);
      

    I hope it helps.