Subclassing Java Classes

javaAdapter(Class super_class , Package package_object )
javaAdapter(Class interface , Package package_object )

When the first parameter of javaAdapter() function is a Class object that represents a class (not interfaces, primitives), javaAdapter() function generates a class that extends the class, and returns an instance. When the first parameter is a Class object that represents an interface, the function generates a class that implements the interface, and returns an instance.

The parameter package_object should be a pnuts.lang.Package object that includes one or more methodName-function mappings. If there is any method in the type hierarchy that can be overriden and matches with a methodName and the number of function parameters in the package_object, the generated class overrides the method to call the function. Otherwise, a new method, like 'public Object methodName(Object, ...)', is defined to do that in the generated class.

The following sample code illustrates how to use script packages in javaAdapter() calls.

e.g.
a = javaAdapter(Object, $(function hello () "hello"))
a.hello()  ==> "hello"
hello()    ==> "hello"

b = javaAdapter(Object, $(`bye = function () "bye"))
b.bye()    ==> "bye"

When a name of a package element includes a method descriptor defined in The Java Virtual Machine Specification, a method with the signature is defined. For example, the following script defines a method 'public void hello(String s) '.

e.g.
p = $()
$.set(p, "hello(Ljava/lang/String;)V", function (x) println("hello " + x))
a = javaAdapter(Object, p)

a.hello("world")

When a script package is constructed in a function, the functions in the script package can access the variables in the closure. This usage can avoid consuming name space by the functions in the script package.

e.g.
function arrayEnum(array) $(
  index = 0,
  function hasMoreElements() index < array.length,
  function nextElement() array[index++]
)
enum = javaAdapter(Enumeration, arrayEnum([1,2,3]))
foreach i (enum) println(i)

javaAdapter() function has the following limitations.


Back