Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Given a name of a Java type, returns an object representing that type in Nashorn. The Java class of the objects used to represent Java types in Nashorn is not Class but rather StaticClass. They are the objects that you can use with the new operator to create new instances of the class as well as to access static members of the class. In Nashorn, Class objects are just regular Java objects that aren't treated specially. Instead of them, StaticClass instances - which we sometimes refer to as "Java type objects" are used as constructors with the new operator, and they expose static fields, properties, and methods. While this might seem confusing at first, it actually closely matches the Java language: you use a different expression (e.g. java.io.File) as an argument in "new" and to address statics, and it is distinct from the Class object (e.g. java.io.File.class). To get StaticClass object corresponding to a Java Class object, you can use "static" property. Below we cover in details the properties of the type objects.

Code Block
titleJava.type
 var arrayListType = Java.type("java.util.ArrayList")
 var intType = Java.type("int")
 var stringArrayType = Java.type("java.lang.String[]")
 var int2DArrayType = Java.type("int[][]")
 
 // Note that the name of the type is always a string for a fully
 // qualified name. 
// You can use any of these types to create
 // new instances, e.g.:
  
 var anArrayList = new Java.type("java.util.ArrayList")
 
 // or

 var ArrayList = Java.type("java.util.ArrayList")
 var anArrayList = new ArrayList
 var anArrayListWithSize = new ArrayList(16)


 var BoolArray = Java.type("boolean[]");
 var arr = new BoolArray(10);
 arr[0] = true;

 // In the special case of inner classes, you can either use the JVM fully 
 // qualified name, // meaning using $ sign in the class name, or you can
 // use the dot:

 var ftype = Java.type("java.awt.geom.Arc2D$Float")
 
 // and this works too:
  
  var ftype = Java.type("java.awt.geom.Arc2D.Float")

 // Java Class object to type:
 // similar to Java.type("java.util.Vector")

 var Class = Java.type("java.lang.Class")
 var VectorClass = Class.forName("java.util.Vector")
 var Vector = VectorClass.static; 

If the type is abstract, you can instantiate an anonymous subclass of it using an argument list that is applicable to any of its public or protected constructors, but inserting a JavaScript object with functions properties that provide JavaScript implementations of the abstract methods. If method names are overloaded, the JavaScript function will provide implementation for all overloads. E.g.:

...