4.5. import class: Import Class from Java

Orc programs can use services of the platform on which the Orc runtime engine runs. In this implementation of Orc, this platform is the Java Runtime Environment (JRE). Java classes may be imported into Orc programs and called as Orc sites.

The declaration import class S = "J" binds the variable S to a site representing the Java class J. Calls to S invoke the corresponding constructor of the Java class J. The created class instance is published from the site call. Instance methods may be invoked on this published value. Calls to S.m invoke the corresponding class static method of the Java class J. The return value of the method is published from the site call. Further details of the Orc-Java interface are in the Java sites section.

4.5.1. Syntax

[27]DeclareClass::= import class Variable = ClassName  

4.5.2. Type

When typechecking declared classes, the Orc typechecker interfaces with the Java type system, so that operations on Java objects typecheck as one would expect in a Java program, with a few exceptions.

  • Methods with return type void in Java have return type Signal in Orc.

  • Interfaces are not fully supported.

  • Type parameter bounds are not supported.

In addition to declaring a site, the import class declaration also declares a type with the same name. It is the Orc type for instances of that Java class. For example, the declaration import class File = java.io.File declares a type File, which is the type of all instances of java.io.File.

If a import class declaration binds a generic Java class, then the corresponding Orc type is instead a type operator, and the constructor site takes type parameters.

Subtyping between Java object types is determined by Java's subtyping relation: if one class is a subclass of another, then that type will be a subtype of the other. The typechecker does not implement a true join operation for Java types; it will find a common ancestor, but not the least common ancestor.

4.5.3. Examples

Invoke a Java constructor and instance method
{- Use a Java class to count the number of tokens in a string -}

import class StringTokenizer = "java.util.StringTokenizer"

-- Invoke a constructor:
val st = StringTokenizer("Elegance is not a dispensable luxury, but a quality that decides between success and failure.", " ")

-- Invoke a method
st.countTokens()

{-
OUTPUT:
15
-}
Invoke a Java static method
{- Use a Java class to calculate a log value -}

import class JavaMath = "java.lang.Math"

-- Invoke a static method:
JavaMath.log10(42.0)

{-
OUTPUT:
1.6232492903979006
-}
Declaring and instantiating a Java generic class
{- Use a Java class to represent tree data structures -}

import class TreeSet = "java.util.TreeSet"

val s = TreeSet[String]()
s.add("Orc") >> s.add("Java") >> s.add("Orc") >> s.size()

{-
OUTPUT:
2
-} 
		

4.5.4. Related Links

Related Reference Topics

Related Tutorial Sections