The recommmended way to access fields uses the namespace-colon syntax described in see Calling Java methods from Scheme. The difference is that instead of a method name following the colon there is field name a following the colon and a period.
To access an static field named field-name
use this syntax
(prefix
:.field-name
instance
)
The prefix
can be as discussed in See Calling Java methods from Scheme.
Here are 5 equivalent ways:
(java.lang.Integer:.MAX_VALUE) (<java.lang.Integer>:.MAX_VALUE) (define-namespace Int32 <java.lang.Integer>) (Int32:.MAX_VALUE) (define-namespace Integer "class:java.lang.Integer") (Integer:.MAX_VALUE) (define-alias <j.l.Integer> <java.lang.Integer>) (<j.l.Integer>:.MAX_VALUE)
You can set a static field using this syntax:
(set! (prefix
:.field-name
)new-value
)
The special field name class
can be used to extract the
java.lang.Class
object for a class-type. For example:
(java.util.Vector:.class) => class java.util.Vector
To access a instance field named field-name
use the following syntax.
Note the period before the field-name
.
(*:.field-name
instance
)
This syntax works with set!
- to set the field use this syntax:
(set! (*:.field-name
instance
)new-value
)
Here is an example:
(define p (list 3 4 5)) (*:.cdr p) => (4 5) (set! (*:.cdr p) (list 6 7)) p => (3 6 7)
You can specify an explicit class:
(prefix
:.field-name
instance
)
If prefix
is bound to <
, then the above
is equivalent to:class
>
(*:.field-name
(as <class
>instance
))
Kawa has both a high-level interface and a low-level interface for accessing the fields of Java objects and static fields. The lower-level interfaces are macros that return functions. These functions can be inlined, producing efficient code. The higher-level functions are less verbose and more convenient.
Function: field
object
fieldname
Get the instance field with the given
fieldname
from the givenObject
. Returns the value of the field, which must be accessible. This procedure has asetter
, and so can be used as the first operand toset!
.The field name is "mangled" (see Mapping Scheme names to Java names) into a valid Java name. If there is no accessible field whose name is
"
, we look for a no-argument method whose name isfieldname
""get
(orFieldname
""is
for a boolean property).Fieldname
"If
object
is a primitive Java array, thenfieldname
can only be'length
, and the result is the number of elements of the array.
Function: static-field
class
fieldname
Get the static field with the given
fieldname
from the givenclass
. Returns the value of the field, which must be accessible. This procedure has asetter
, and so can be used as the first operand toset!
.If the
fieldname
is the special nameclass
, then it returns thejava.lang.Class
object corresponding toclass
(which is usually agnu.bytecode.ClassType
object).
Examples:
(static-field <java.lang.System> 'err) ;; Copy the car field of b into a. (set! (field a 'car) (field b 'car))