Using Scripted Classes from Java

Scripted classes can be used from Java by following a few steps described below.

Steps

1. Set up a Context that will be referenced during script execution

In this step, a context that will be referenced during script execution is prepared and associated with the current thread by calling Runtime.setThreadContext().

import pnuts.lang.Context;
import pnuts.lang.Runtime;

Context context = new Context();
Runtime.setThreadContext(context);
context.usePackage("pnuts.tools"); // specifies which module is used

2. Create a ClassLoader

In this step, a ClassLoader is created, which can parse/compile/load scripted classes.

ClassLoader classLoadser = Pnuts.createClassLoader(context);
Thread.currentThread().setContextClassLoader(classLoader);
Class cls = classLoader.loadClass(className);

An Example

mymap.pnc
import java.util.*
class mymap extends TreeMap {
  get(key){
    if ((v = super.get(key)) == null){
      super.put(key, v = set())
    }
    v
  }
}
MyTest.java
import pnuts.lang.Context;
import pnuts.lang.Runtime;
import java.util.Map;
 
public class MyTest {
   static Context setupContext(){
      Context context = new Context();
      context.usePackage("pnuts.tools");
      return context;
   }
   public static void main(String[] args) throws Exception {
      Context context = setupContext();
      Runtime.setThreadContext(context);
      ClassLoader parent = Thread.currentThread().getContextClassLoader();
      ClassLoader cloader = Pnuts.createClassLoader(context, parent);
      Thread.currentThread().setContextClassLoader(cloader);
      Class cls = cloader.loadClass(args[0]);
      Map m = (Map)cls.newInstance();
      System.out.println(m.get("no_such_key"));
   }
}
C:\> set CLASSPATH=pnuts.jar;pnuts-modules.jar;.
C:\> java MyTest mymap