Java Reference
In-Depth Information
Accessing methods and properties of Java objects is similar in most scripting
languages. Some scripting languages let you invoke getter and setter methods on an
object using the property name. The following code in Nashorn creates a java.util.Date
object and accesses the object's method using both the property names and the method
names. You may get a different output because the code operates on the current date:
var LocalDate = Java.type("java.time.LocalDate");
var dt = LocalDate.now();
var year = dt.year; // Use as a property
var month = dt.month; // Use as a property
var date = dt.getDayOfMonth(); // Use as a method
print("Date:" + dt);
print("Year:" + year + ", Month:" + month + ", Day:" + date);
Date:2014-10-12
Year:2014, Month:OCTOBER, Day:12
In JavaScript, you can use the methods of Java objects as if they are properties. When
you are reading the property named xxx , JavaScript will automatically call the getXxx()
method. When you are setting the property named xxx , the setXxx() method will be
called. The JavaBeans method convention is used to find the corresponding method.
For example, if you read the leapYear property of a LocalDate object, the object's
isLeapYear() method will be called because the property is of the boolean type.
When using JavaScript, it is important to understand the different types of String
objects. A String object may be a JavaScript String object or a Java java.lang.String
object. JavaScript defines a length property for its String object, whereas Java has a
length() method for its java.lang.String class. The following snippet of code shows
the difference in creating and accessing the length of a JavaScript String and a Java
java.lang.String objects:
// JavaScript String
var jsStr = new String("Hello JavaScript String");
print("JavaScript String: " + jsStr);
print("JavaScript String Length: " + jsStr.length);
// Java String
var javaStr = new java.lang.String("Hello Java String");
print("Java String: " + javaStr);
print("Java String Length: " + javaStr.length());
JavaScript String: Hello JavaScript String
JavaScript String Length: 23
Java String: Hello Java String
Java String Length: 17
 
Search WWH ::




Custom Search