| Version: | 1.0-11 |
| Title: | Low-Level R to Java Interface |
| Author: | Simon Urbanek <simon.urbanek@r-project.org> |
| Maintainer: | Simon Urbanek <simon.urbanek@r-project.org> |
| Depends: | R (≥ 3.6.0), methods |
| Description: | Low-level interface to Java VM very much like .C/.Call and friends. Allows creation of objects, calling methods and accessing fields. |
| License: | LGPL-2.1 |
| URL: | http://www.rforge.net/rJava/ |
| SystemRequirements: | Java JDK 1.2 or higher (for JRI/REngine JDK 1.4 orhigher), GNU make |
| BugReports: | https://github.com/s-u/rJava/issues |
| NeedsCompilation: | yes |
| Packaged: | 2024-01-25 22:25:37 UTC; rforge |
| Repository: | CRAN |
| Date/Publication: | 2024-01-26 16:02:25 UTC |
Invoke Java Garbage Collection
Description
.jgc invokes the R and Java garbage collectors.
Usage
.jgc(R.gc = TRUE, ...)Arguments
R.gc | logical, if |
... | any additional parameters passed to |
Details
.jgc invokes the R garbage collector (unlessR.gc=FALSE) which removes any unused Java references and theninvokes the Java garbage collector to reclaim Java heap space.
Author(s)
Simon Urbanek
Is a java object an instance of a given java class
Description
Is a java object an instance of a given java class
Usage
o %instanceof% cl.jinstanceof( o, cl )Arguments
o | java object reference |
cl | java class. This can be a character vector of length onegiving the name of the class, or another java object, or an instanceof the Class class, or a object of class |
Value
TRUE if o is an instance of cl
Author(s)
Romain Francois <francoisromain@free.fr>
Examples
Double <- J("java.lang.Double")d <- new( Double, "10.2" )# characterd %instanceof% "java.lang.Double"d %instanceof% "java.lang.Number"# jclassNamed %instanceof% Double# instance of ClassDouble.class <- Double@jobjd %instanceof% Double.class# other objectother.double <- new( Double, 10.2 )d %instanceof% other.doubleException handling
Description
R handling of java exception
Usage
## S3 method for class 'Throwable'x$name ## S3 replacement method for class 'Throwable'x$name <- valueArguments
x | condition |
name | ... |
value | ... |
Details
Java exceptions are mapped to R conditions that are relayed by thestop function.
The R condition contains the actual exception object as thejobj item.
The class name of the R condition is made of a vector of simple java class names, the class names without their packagepath. This allows the R code to use direct handlers similar to direct exception handlers in java. See the example below.
Examples
Integer <- J("java.lang.Integer")tryCatch( Integer$parseInt( "10.." ), NumberFormatException = function(e){e$jobj$printStackTrace() } )# the dollar method is also implemented for Throwable conditions, # so that syntactic sugar can be used on condition objects# however, in the example below e is __not__ a jobjRef object referencetryCatch( Integer$parseInt( "10.." ), NumberFormatException = function(e){e$printStackTrace() } )High level API for accessing Java
Description
J creates a Java class reference or calls a Java method
Usage
J(class, method, ..., class.loader=.rJava.class.loader)Arguments
class | java object reference or fully qualified class name in JNInotation (e.g "java/lang/String" ) or standard java notation (e.g"java.lang.String") |
method | if present then |
... | optional parameters that will be passed to the method (if the |
class.loader | optional, custom loader to use if a class look-upis necessary (i.e., if |
Details
J is the high-level access to Java.
If themethod argument is missing thencode must be aclass name andJ creates a class name reference that can beused either in a call tonew to create a new Java object(e.g.new(J("java.lang.String"), "foo")) or with$operator to call a static method(e.g.J("java.lang.Double")$parseDouble("10.2").)
If themethod argument is present then it must be a stringvector of length one which defines the method to be called on theobject.
Value
Ifmethod is missing the the returned value is an object ofthe classjclassName. Otherwise the value is the result ofthe method invocation. In the latter case Java exceptions may bethrown and the function doesn't return.
Note
J is a high-level API which is slower than.jnewor.jcall since it has to use reflection to find themost suitable method.
See Also
Examples
if (!nzchar(Sys.getenv("NOAWT"))) { f <- new(J("java.awt.Frame"), "Hello") f$setVisible(TRUE)}J("java.lang.Double")$parseDouble("10.2")J("java.lang.Double", "parseDouble", "10.2" )Double <- J("java.lang.Double")Double$parseDouble( "10.2")# String[] strings = new String[]{ "string", "array" } ; strings <- .jarray( c("string", "array") )# this uses the JList( Object[] ) constructor # even though the "strings" parameter is a String[] l <- new( J("javax.swing.JList"), strings)Field/method operator for Java objects
Description
The$ operator forjobjRef Java object references provides convenience access to object attributes and calling Java methods.
Usage
## S3 method for class 'jobjRef' .DollarNames(x, pattern = "" )## S3 method for class 'jarrayRef' .DollarNames(x, pattern = "" )## S3 method for class 'jrectRef' .DollarNames(x, pattern = "" )## S3 method for class 'jclassName'.DollarNames(x, pattern = "" )Arguments
x | object to complete |
pattern | pattern |
Details
rJava provides two levels of API: low-level JNI-API in the form of.jcall function and high-level reflection API based on the$ operator. The former is very fast, but inflexible. The latter is a convenient way to use Java-like programming at the cost of performance. The reflection API is build around the$ operator onjobjRef-class objects that allows to access Java attributes and call object methods.
$ returns either the value of the attribute or calls a method, depending on which name matches first.
$<- assigns a value to the corresponding Java attribute.
names and.DollarNames returns all fields and methods associated with the object.Method names are followed by( or() depending on arity.This use of names is mainly useful for code completion, it is not intended to be used programmatically.
This is just a convenience API. Internally all calls are mapped into.jcall calls, therefore the calling conventions and returning objects use the same rules. For time-critical Java calls.jcall should be used directly.
Methods
$signature(x = "jobjRef"): ...$signature(x = "jclassName"): ...$<-signature(x = "jobjRef"): ...$<-signature(x = "jclassName"): ...namessignature(x = "jobjRef"): ...namessignature(x = "jarrayRef"): ...namessignature(x = "jrectRef"): ...namessignature(x = "jclassName"): ...
See Also
Examples
v <- new(J("java.lang.String"), "Hello World!")v$length()v$indexOf("World")names(v)J("java.lang.String")$valueOf(10)Double <- J("java.lang.Double")# the class pseudo field - instance of Class for the associated class# similar to java Double.classDouble$classConverts java objects or arrays to R lists
Description
as.list is implemented for java objects and java arraysto facilitate usinglapply calls over elements of a java arrayor items of an Iterator associated with an Iterable object
For java array references,as.list is mapped to.jevalArray
For java objects that implement the Iterable interface, the list is created by iterating over the associated iterator
Usage
## S3 method for class 'jobjRef'as.list(x, ...)## S3 method for class 'jarrayRef'as.list(x, ...)Arguments
x | java array or Iterable java object |
... | ignored |
Value
An R list, or vector.
Note
The function is not intended to be called directly. It is implementedso that java arrays or Iterable java objects can be used as the first argument oflapply
See Also
Examples
# lapplying over a java array a <- .jarray( list( .jnew( "java/awt/Point", 10L, 10L ), .jnew( "java/awt/Point", 30L, 30L ) ) ) lapply( a, function(point){ with(point, { (x + y ) ^ 2} ) } )# lapply over a Vector (implements Iterable)v <- .jnew("java/util/Vector")v$add( "foo" )v$add( .jnew("java/lang/Double", 10.2 ) )sapply( v, function(item) item$getClass()$getName() )Object cloner
Description
Generic function to clone objects
Usage
clone(x, ...)Arguments
x | An object to clone |
... | Further arguments, ignored |
Value
A clone of the object
Methods
- clone
signature(x = "jobjRef"): clone a java object reference (must implement Cloneable)- clone
signature(x = "jarrayRef"): clone a java rugged array (not yet implemented)- clone
signature(x = "jrectRef"): clone a java rectangular array (not yet implemented)
Warning
The implementation of clone for java object references usesthe clone method of the Object class. The reading of its descriptionin the java help page isstrongly recommended.
Examples
p1 <- .jnew("java/awt/Point" ) p2 <- clone( p1 ) p2$move( 10L, 10L ) p1$getX() # check that p1 and p2 are not references to the same java object stopifnot( p1$getX() == 0 ) stopifnot( p2$getX() == 10 )Java array handling functions
Description
.jarray takes a vector (or a list of Java references) as itsargument, creates a Java array containing the elements of the vector(or list) and returns a reference to such newly created array.
.jevalArray takes a reference to a Java array and returns itscontents (if possible).
Usage
.jarray(x, contents.class = NULL, dispatch = FALSE).jevalArray(obj, rawJNIRefSignature = NULL, silent = FALSE, simplify = FALSE)Arguments
x | vector or a list of Java references |
contents.class | common class of the contained objects, seedetails |
obj | Java object reference to an array that is to be evaluated |
rawJNIRefSignature | JNI signature that would be used forconversion. If set to |
silent | if set to true, warnings are suppressed |
dispatch | logical. If |
simplify | if set to |
Details
.jarray: The input can be either a vector of some sort (such asnumeric, integer, logical, ...) or a list of Java references. Thecontents is pushed to the Java side and a corresponding array iscreated. The type of the array depends on the input vector type. Forexample numeric vector createsdouble[] array, integer vectorcreatesint[] array, character vectorString[] array andso on. Ifx is a list, it must contain Java references only (orNULLs which will be treated asNULL references).
Thecontents.class parameter is used only ifx is a listof Java object references and it can specify the class that will beused for all objects in the array. If set toNULL no assumptionis made andjava/lang/Object will be used. Use with care andonly if you know what you're doing - you can always use.jcast to cast the entire array to another type even ifyou use a more general object type. One typical use is to constructmulti-dimensional arrays which mandates passing the array type ascontents.class.
The result is a reference to the newly created array.
The inverse function which fetches the elements of an array referenceis.jevalArray.
.jevalArray currently supports only a subset of all possiblearray types. Recursive arrays are handled by returning a list ofreferences which can then be evaluated separately. The only exceptionissimplify=TRUE in which case.jevalArray attempts toconvert multi-dimensional arrays into native R type if there is asuch. This only works for rectangular arrays of the same basic type(i.e. the length and type of each referenced array is the same -sometimes matrices are represented that way in Java).
Value
.jarray returns a Java array reference (jarrayRef orjrectRef) to anarray created with the supplied contents.
.jevalArray returns the contents of the array object.
Examples
a <- .jarray(1:10)print(a).jevalArray(a)b <- .jarray(c("hello","world"))print(b)c <- .jarray(list(a,b))print(c)# simple .jevalArray will return a list of referencesprint(l <- .jevalArray(c))# to convert it back, use lapplylapply(l, .jevalArray)# two-dimensional array resulting in int[2][10]d <- .jarray(list(a,a),"[I")print(d)# use dispatch to convert a matrix to [[De <- .jarray(matrix(1:12/2, 3), dispatch=TRUE)print(e)# simplify it back to a matrix.jevalArray(e, simplify=TRUE)Class "jarrayRef" Reference to an array Java object
Description
This class is a subclass ofjobjRef-class and represents a reference to an array Java object.
Objects from the Class
Objects cannot be created directly, but only as the returnvalue of.jcall function.
Slots
jsig:JNI signature of the array type
jobj:Internal identifier of the object
jclass:Inherited from
jobjRef, but unspecified
Methods
- [
signature(x = "jarrayRef"):not yet implemented- [[
signature(x = "jarrayRef"): R indexing of java arrays- [[<-
signature(x = "jarrayRef"): replacement methodheadsignature(x = "jarrayRef"): head of the java arraytailsignature(x = "jarrayRef"): tail of the java array- length
signature(object = "jarrayRef"): Number of java objects in the java array- str
signature(object = "jarrayRef"): ...- unique
signature(x = "jarrayRef"):not yet implemented- duplicated
signature(x = "jarrayRef"):not yet implemented- anyDuplicated
signature(x = "jarrayRef"):not yet implemented- sort
signature(x = "jarrayRef"):not yet implemented- rev
signature(x = "jarrayRef"):not yet implemented- min
signature(x = "jarrayRef"):not yet implemented- max
signature(x = "jarrayRef"):not yet implemented- range
signature(x = "jarrayRef"):not yet implemented
Extends
Class"jobjRef", directly.
Author(s)
Simon Urbanek
See Also
.jcall orjobjRefjrectRef for rectangular arrays
java tools used internally in rJava
Description
java tools used internally in rJava
Examples
Attach mechanism for java packages
Description
ThejavaImport function creates an item on R'ssearch that maps names to class names references found in one or several "imported" java packages.
Usage
javaImport(packages = "java.lang")Arguments
packages | character vector containing java package paths |
Value
An external pointer to a java specificUserDefinedDatabase object
Warning
This feature is experimental. Use with caution, and don't forget todetach.
Note
Currently the list of objects in the imported package is populatedas new objects are found,not at creation time.
Author(s)
Romain Francois <francoisromain@free.fr>
References
User-Defined Tables in the R Search Path. Duncan Temple Lang. December 4, 2001https://www.omegahat.net/RObjectTables/
See Also
Examples
## Not run: attach( javaImport( "java.util" ), pos = 2 , name = "java:java.util" )# now we can just do something like this v <- new( Vector )v$add( "foobar" )ls( pos = 2 )# or thism <- new( HashMap )m$put( "foo", "bar" )ls( pos = 2 )# or even this :Collections$EMPTY_MAP## End(Not run)Call a Java method
Description
.jcall calls a Java method with the supplied arguments.
Usage
.jcall(obj, returnSig = "V", method, ..., evalArray = TRUE, evalString = TRUE, check = TRUE, interface = "RcallMethod", simplify = FALSE, use.true.class = FALSE)Arguments
obj | Java object ( |
returnSig | Return signature in JNI notation (e.g. "V" for void,"[I" for |
method | The name of the method to be called |
... | Any parameters that will be passed to the Java method. The parametertypes are determined automatically and/or taken from the |
evalArray | This flag determines whether the array return valueis evaluated ( |
simplify | If |
evalString | This flag determines whether string result is returnedas characters or as Java object reference. |
check | If set to |
interface | This option is experimental and specifies theinterface used for calling the Java method; the currentimplementation supports two interfaces:
|
use.true.class | logical. If set to |
Details
.jcall requires exact match of argument and return types. Forhigher efficiency.jcall doesn't perform any lookup in thereflection tables. This means that passing subclasses of the classespresent in the method definition requires explicit casting using.jcast. Passingnull arguments also needs aproper class specification with.jnull.
Java typeslong andfloat have no corresponding types inR and therefore any such parameters must be flagged as such using.jfloat and.jlong functions respectively.
Java also distinguishes scalar and array types whereas R doesn't havethe concept of a scalar. In R a scalar is basically a vector (calledarray in Java-speak) of the length 1. Therefore passing vectors of thelength 1 is ambiguous..jcall assumes that any vector of thelength 1 that corresponds to a native Java type is a scalar. All othervectors are passed as arrays. Therefore it is important to use.jarray if an arbitrary vector (including those of thelength 1) is to be passed as an array parameter.
Important note about encoding of character vectors:Java interface always works with strings in UTF-8 encoding, thereforethe safest way is to run R in a UTF-8 locale. If that is notpossible for some reason, rJava can be used in non-UTF-8 locales,but care must be taken. Since R 2.7.0 it is possible to associateencoding with strings and rJava will flag all strings it produceswith the appropriate UTF-8 tag. R will then perform correspondingappropriate conversions where possible (at a cost of speed andmemory usage), but 3rd party code may not (e.g. olderpackages). Also rJava relies on correct encoding flags for stringspassed to it and will attempt to perform conversions wherenecessary. If some 3rd party code produces strings incorrectlyflagged, all bets are off.
Finally, for performance reasons class, method and field names aswell as signatures are not always converted and should not containnon-ASCII characters.
Value
Returns the result of the method.
See Also
Examples
.jcall("java/lang/System","S","getProperty","os.name")if (!nzchar(Sys.getenv("NOAWT"))) { f <- .jnew("java/awt/Frame","Hello") .jcall(f,,"setVisible",TRUE)}Cast a Java object to another class
Description
.jcast returns a Java object reference cast to another Java class.
Usage
.jcast(obj, new.class = "java/lang/Object", check = FALSE, convert.array = FALSE)Arguments
obj | a Java object reference |
new.class | fully qualified class name in JNI notation(e.g. |
check | logical. If |
convert.array | logical. If |
Details
This function is necessary if a argument of.jcall or.jnew is defined as the superclass of the object to bepassed (see.jcall). The original object is not modified.
The default values for the argumentscheck andconvert.arrayisFALSE in order to guarantee backwards compatibility, but it is recommended to set the arguments toTRUE
Value
Returns a Java object reference (jobjRef) to the objectobj, changing the object class.
See Also
Examples
## Not run: v <- .jnew("java/util/Vector").jcall("java/lang/System","I","identityHashCode",.jcast(v, "java/lang/Object"))## End(Not run)Ensures that a given object is an array reference
Description
.jcastToArray takes a Java object reference of any kind andreturns Java array reference if the given object is a reference to anarray.
Usage
.jcastToArray(obj, signature=NULL,, quiet=FALSE)Arguments
obj | Java object reference to cast or a scalar vector |
signature | array signature in JNI notation (e.g. |
class | force the result to pose as a particular Javaclass. This has the same effect as using |
quiet | if set to |
Details
Sometimes a result of a method is by definition of the classjava.lang.Object, but the actual referenced object may be anarray. In that case the method returns a Java object reference insteadof an array reference. In order to obtain an array reference, it isnecessary to cast such an object to an array reference - this is doneusing the above.jcastToArray function.
The input is an object reference that points to an array. Usually thesignature should be left atNULL such that it is determinedfrom the object's class. This is also a check, because if the object'sclass is not an array, then the functions fails either with an error(whenquiet=FALSE) or by returning the original object (whenquiet=TRUE). If the signature is set to anything else, it isnot verified and the array reference is always created, even if it maybe invalid and unusable.
For convenience.jcastToArray also accepts non-references inwhich case it simply calls.jarray, ignoring all otherparameters.
Value
Returns a Java array reference (jarrayRef) on success. Ifquiet isTRUE then the result can also be the originalobject in the case of failure.
Examples
## Not run: a <- .jarray(1:10)print(a)# let's create an array containing the arrayaa <- .jarray(list(a))print(aa)ba <- .jevalArray(aa)[[1]]# it is NOT the inverse, because .jarray works on a list of objectsprint(ba)# so we need to cast the object into an arrayb <- .jcastToArray(ba)# only now a and b are the same array referenceprint(b)# for convenience .jcastToArray behaves like .jarray for non-referencesprint(.jcastToArray(1:10/2))## End(Not run)Java exception handling
Description
.jcheck checks the Java VM for any pending exceptions andclears them.
.jthrow throws a Java exception.
.jgetEx polls for any pending exceptions and returns the exception object.
.jclear clears a pending exception.
Usage
.jcheck(silent = FALSE).jthrow(exception, message = NULL).jgetEx(clear = FALSE).jclear()Arguments
silent | If set to |
exception | is either a class name of an exception to create or athrowable object reference that is to be thrown. |
message | if |
clear | if set to |
Details
Please note that some functions (such as.jnew or.jcall) call.jcheck implicitly unlessinstructed to not do so. If you want to handle Java exceptions, youshould make sure that those function don't clear the exception you maywant to catch.
The exception handling is still as a very low-level and experimental,because it requires polling of exceptions. A more elaborate systemusing constructs similar totry ...catch is planned fornext major version ofrJava.
Warning: When requesting exceptions to not be clearedautomatically, please note that theshow method (which iscalled byprint) has a side-effect of making a Java call to getthe string representation of a Java object. This implies that it willbe impeded by any pending exceptions. Therefore exceptions obtainedthrough.jgetEx can be stored, but should not be printed(or otherwise used in Java calls) until after the exception iscleared. In general, all Java calls will fail (possibly silently)until the exception is cleared.
Value
.jcheck returnsTRUE if an exception occurred orFALSE otherwise.
.jgetEx returnsNULL if there are no pending exceptionsor an object of the class "java.lang.Throwable" representing thecurrent exception.
See Also
Examples
# we try to create a bogus object and# instruct .jnew to not clear the exception# this will raise an exceptionv <- .jnew("foo/bar", check=FALSE)# you can poll for the exception, but don't try to print it# (see details above)if (!is.null(e<-.jgetEx())) print("Java exception was raised")# expect TRUE result here because the exception was still not clearedprint(.jcheck(silent=TRUE))# next invocation will be FALSE because the exception is now clearedprint(.jcheck(silent=TRUE))# now you can print the actual expection (even after it was cleared)print(e)Class "jclassName" - a representation of a Java class name
Description
This class holds a name of a class in Java.
Objects from the Class
Objects of this class should *not* be created directly. Instead, thefunctionJ should be used to create new objects of this class.
Slots
name:Name of the class (in source code notation)
jobj:Object representing the class in Java
Methods
The objects of classjclassName are used indirectly to be ableto create new Java objects vianew such asnew(J("java.lang.String"), "foo") or to use the$convenience operator on static classes, such asJ("java.lang.Double")$parseDouble("10.2").
as.charactersignature(x = "jclassName"):returns the class name as a string vector of length one.
Author(s)
Simon Urbanek
See Also
Java callback engineCast a Java object to another class
Description
.jengine obtains the current callback engine or starts it.
Usage
.jengine(start=FALSE, silent=FALSE)Arguments
start | if set to |
silent | if set to |
Details
.jengine can be used to detect whether the engine was startedor to start the engine.
Before any callbacks from Java into R can be performed, the Javacallback engine must be initialized, loading Java/R Interface(JRI). If JRI was not started andstart is set toTRUEthen.jengine will load necessary classes and startit.
Note that JRI is an optional part of rJava and requires R sharedlibrary at the moment. By default rJava will continue withinstallation even if JRI cannot be built.
Value
Returns a Java object reference (jobjRef) to the current Javacallback engine.
See Also
Examples
## Not run: .jengine(TRUE)## End(Not run)Comparing Java References
Description
.jequals function can be used to determine whether two objectsare equal. In addition, it allows mixed comparison of non-Java objectfor convenience, unless strict comparison is desired.
The binary operators== and!= are mapped to(non-strict) call to.jequals for convenience.
.jcompare compares two objects in the sense of thejava.lang.Comparable interface.
The binary operators<,>,<=,>= are mapped to calls to.jcompare for convenience
Usage
.jequals(a, b, strict = FALSE).jcompare( a, b )Arguments
a | first object |
b | second object |
strict | when set to |
Details
.jequals compares two Java objects by callingequalsmethod of one of the objects and passing the other object as itsargument. This allows Java objects to define the ‘equality’ inobject-dependent way.
In addition,.jequals allows the comparison of Java object toother scalar R objects. This is done by creating a temporary Javaobject that corresponds to the R object and using it for a call to theequals method. If such conversion is not possible a warning isproduced and the result itFALSE. The automatic conversionwill be avoided ifstrict parameter is set toTRUE.
NULL values ina orb are replaced by Javanull-references and thus.jequals(NULL,NULL) isTRUE.
If neithera andb are Java objects (with the exceptionof both beingNULL) then the result is identical to that ofall.equal(a,b).
Neither comparison operators nor.jequals supports vectors andreturnsFALSE in that case. A warning is also issued unlessstrict comparison was requested.
Value
.jequals returnsTRUE if both object are considered equal,FALSE otherwise.
.jcompare returns the result of thecompareTo java methodof the object a applied to b
Methods
- !=
signature(e1 = "ANY", e2 = "jobjRef"): ...- !=
signature(e1 = "jobjRef", e2 = "jobjRef"): ...- !=
signature(e1 = "jobjRef", e2 = "ANY"): ...- ==
signature(e1 = "ANY", e2 = "jobjRef"): ...- ==
signature(e1 = "jobjRef", e2 = "jobjRef"): ...- ==
signature(e1 = "jobjRef", e2 = "ANY"): ...- <
signature(e1 = "ANY", e2 = "jobjRef"): ...- <
signature(e1 = "jobjRef", e2 = "jobjRef"): ...- <
signature(e1 = "jobjRef", e2 = "ANY"): ...- >
signature(e1 = "ANY", e2 = "jobjRef"): ...- >
signature(e1 = "jobjRef", e2 = "jobjRef"): ...- >
signature(e1 = "jobjRef", e2 = "ANY"): ...- >=
signature(e1 = "ANY", e2 = "jobjRef"): ...- >=
signature(e1 = "jobjRef", e2 = "jobjRef"): ...- >=
signature(e1 = "jobjRef", e2 = "ANY"): ...- <=
signature(e1 = "ANY", e2 = "jobjRef"): ...- <=
signature(e1 = "jobjRef", e2 = "jobjRef"): ...- <=
signature(e1 = "jobjRef", e2 = "ANY"): ...
Note
Don't usex == NULL to check fornull-references, becausex could beNULL and thusthe result would be an empty vector. Useis.jnullinstead.(In theoryis.jnull andx == .jnull() are the the same,butis.jnull is more efficient.)
See Also
Examples
s <- .jnew("java/lang/String", "foo").jequals(s, "foo") # TRUE.jequals(s, "foo", strict=TRUE) # FALSE - "foo" is not a Java objectt <- s.jequals(s, t, strict=TRUE) # TRUEs=="foo" # TRUEDouble <- J("java.lang.Double")d1 <- new( Double, 0.0 ) d2 <- new( Double, 1.0 )d3 <- new( Double, 0.0 )d1 < d2d1 <= d3d1 >= d3d1 > d2# cannot compare a Double and a Stringtry( d1 < "foo" )# but can compare a Double and an Integerd1 < 10LObtains the value of a field
Description
.jfield returns the value of the specified field on an object.
Usage
.jfield(o, sig = NULL, name, true.class = is.null(sig), convert = TRUE)`.jfield<-`(o, name, value)Arguments
o | Class name or object (Java reference) whose field is to beaccessed. Static fields are supported both by specifying the classname or using an instance. |
sig | signature (JNI type) of the field. If set to |
name | name of the field to access |
true.class | by default the class of the resulting object matchesthe signature of the field. Setting this flag to |
convert | when set to |
value | value to assign into the field. The field signature isdetermined from the value in the same way that parameter signaturesare determined in |
Details
The detection of a field signature in.jfield using reflectionis considerably expensive (more than 3 additional method calls have tobe performed), therefore it is recommended for time-critical code tospecify the field signature beforehand.
NOTE: The sequence of arguments in.jfield has been changedsince rJava 0.5 to be more consistent and match the sequence in.jcall. Also.jsimplify is no longer needed as primitivetypes are obtained directly.
Value
.jfield: contents of the field,.jfield<-: modified object.
See Also
Examples
## Not run: .jfield("java/lang/Boolean",, "TYPE")## End(Not run)Wrap numeric vector as flat Java parameter
Description
.jfloat marks a numeric vector as an object that can be usedas parameter to Java calls that requirefloat parameters.Similarly,.jlong marks a numeric vector aslongparameter,.jshort asshort and.jbyte asbyte.
Usage
.jfloat(x).jlong(x).jbyte(x).jchar(x).jshort(x)Arguments
x | numeric vector |
Details
R has no nativefloat orlong type. Numeric vectors arestored asdoubles, hence there is no native way to pass floatnumbers to Java methods. The.jfloat call marks a numericvector as having the Java typefloat by wrapping it in thejfloat class. The class is still a subclass ofnumeric,therefore all regular R operations are unaffected by this.
Similarly,.jlong is used to mark a numeric vector as aparameter of thelong Java type. Please note that in general Rhas no native type that will hold along value, so conversionbetween Java'slong type and R's numeric is potentially lossy.
.jbyte is used when a scalar byte is to be passed to Java. Notethat byte arrays are natively passed as raw vectors, not as.jbyte arrays, although non-scalar.jbyte is equivalentexcept for using four-times as much memory.
.jchar is strictly experimental and uses integer vector asstorage class. The typechar in Javarepresents 16-bit Unicode code points (not to be confused withchar in C which isbyte in Java!), see Javadocumentation for details.x can also be a non-NA stringin which case.jchar(x) is just a shorthand for.jnew("java.lang.String", x)$toCharArray() and thus performs aJava call (unlike all other functions mentioned here).
Value
Returns a numeric vector of the classjfloat,jlong,jbyte,jshort orjcharthat can be used as parameter to Java calls that requirefloat,long,byte,short orcharparameters respectively.
See Also
Classes "jfloat", "jlong", "jbyte" and "jchar" specify Javanative types that are not native in R
Description
These classes wrap a numeric vector to be treated asfloat orlong argument when passed to Java and aninteger vector to be treated asbyte orchar. R doesn'tdistinguish betweendouble andfloat, but Javadoes. In order to satisfy object types, numeric vectors that should beconverted to floats or long on the Java side must be wrapped in thisclass. In additionjbyte must be used when passing scalar byte(but not byte arrays, those are mapped into RAW vectors). Finallyjchar it used when mapping integer vectors into unicode Javacharacter vectors.
Objects from the Class
Objects can be created by calling.jfloat,.jlong,.jbyte or.jcharrespectively.
Slots
.Data:Payload
Extends
"jfloat" and "jlong":Class"numeric", from data part.Class"vector", by class"numeric".
"jbyte" and "jchar":Class"integer", from data part.Class"vector", by class"integer".
Methods
"jfloat" and "jlong" have no methods other than those inherited from "numeric"."jbyte" and "jchar" have no methods other than those inherited from "integer".
Author(s)
Simon Urbanek
See Also
.jfloat,.jlong,.jbyte,.jchar and.jcall
Initialize Java VM
Description
.jinit initializes the Java Virtual Machine (JVM). Thisfunction must be called before any rJava functions can be used.
.jvmState() returns the state of the current JVM.
Usage
.jinit(classpath = NULL, parameters = getOption("java.parameters"), ...,silent = FALSE, force.init = FALSE).jvmState()Arguments
classpath | Any additional classes to include in the Java classpaths (i.e. locations of Java classes to use). This path will beprepended to paths specified in the |
parameters | character vector of parameters to be passed tothe virtual machine. They are implementation dependent and applyto JDK version 1.2 or higher only. Please note that each parametermust be in a separate element of the array, you cannot use aspace-separated string with multiple parameters. |
... | Other optional Java initialization parameters (implementation-dependent). |
silent | If set to |
force.init | If set to |
Details
Starting with version 0.5 rJava provides a custom class loader that canautomatically track classes and native libraries that are provided inR packages. Therefore R packages should NOT use.jinit, butcall.jpackage instead. In addition this allows the useof class path modifying function.jaddClassPath.
Important note: if a class is found on the system class path (i.e. ontheclasspath specified to.jinit) then the system classloader is used instead of the rJava loader, which can lead to problemswith reflection and native library support is not enabled. Thereforeit is highly recommended to use.jpackage or.jaddClassPath instead ofclasspath (save for systemclasses).
Stating with version 0.3-8 rJava is now capable of modifying the classpath on the fly for certain Sun-based Java virtual machines, even whenattaching to an existing VM. However, this is done by exploiting theway ClassLoader is implemented and may fail in the future. In generalit is officially not possible to change the class path of a runningVM.
At any rate, it is impossible to change any other VM parameters of arunning VM, so when using.jinit in a package, be generous withlimits and don't use VM parameters to unnecessarily restrictresources (or preferably use.jpackage instead). JVMparameters can only be set if the initial state of the JVM is"none".
There is a subtle difference between"initialized" and the JVMstate. It is in theory possible for"initialized" to beFALSE and still"state" to be"created" or"attached" in case where JVM was created but rJava has not beenable to initialize for other reasons, although such state should berare and problematic in either case. Behavior of rJava functions otherthan.jinit and.jvmState is undefined unless.jvmState()$initialized isTRUE.
Value
The return value is an integer specifying whether and how the VM wasinitialized. Negative values indicate failure, zero denotes successfulinitialization and positive values signify partially successfulinitilization (i.e. the VM is up, but parameters or class path couldnot be set due to an existing or incompatible VM).
.jvmState returns a named list with at least the followingelements:
initialized |
|
state | string representing the current state of the JVM. One ofthe following values: |
See Also
Examples
## Not run: ## set heap size limit to 512MB (see java -X) and## use "myClasses.jar" as the class path.jinit(classpath="myClasses.jar", parameters="-Xmx512m").jvmState()## End(Not run)rJava memory profiler
Description
.jmemprof enables or disables rJava memory profiling. If rJavawas compiled without memory profiling support, then a call to thisfunction always causes an error.
Usage
.jmemprof(file = "-")Arguments
file | file to write profiling information to or |
Details
Thefile parameter must be either a filename (which will beopened in append-mode) or "-" to use standard output orNULL todisable profiling. An empty string "" is equivalent toNULL inthis context.
Note that lots of finalizers are run only when R exists, so usuallyyou want to enable profiling early and let R exit to get a sensibleprofile. Running gc may be helpful to get rid of references that canbe collected in R.
A simple perl script is provided to analyze the result of theprofiler. Due to its simple text format, it is possible to captureentire stdout including the profiler information to have both theconsole context for the allocations and the profile. Memory profilingis also helpful if rJava debug is enabled.
Note that memory profiling support must be compiled in rJava and it isby default compiled only if debug mode is enabled (which is not thecase by default).
Value
ReturnsNULL.
Examples
## memory profiling support is optional so only works when enabledtryCatch(.jmemprof("rJava.mem.profile.txt"),error=function(e) message(e))Create a Java object
Description
.jnew create a new Java object.
Usage
.jnew(class, ..., check=TRUE, silent=!check, class.loader=NULL)Arguments
class | fully qualified class name in JNI notation (e.g. |
... | Any parameters that will be passed to the correspondingconstructor. The parameter types are determined automatically and/ortaken from the |
check | If set to |
silent | If set to |
class.loader | optional class loader to force for loading theclass. If not set, the rJava class loader is used first. The defaultJava class loader is always used as a last resort. Set to |
Value
Returns the reference (jobjRef) to the newly created object ornull-reference (see.jnull) if something went wrong.
See Also
Examples
## Not run: f <- .jnew("java/awt/Frame","Hello").jcall(f,,"setVisible",TRUE)## End(Not run)Java null object reference
Description
.jnull returns anull reference of a specified classtype. The resulting object is of the classjobjRef.
is.jnull is an extension ofis.null that also returnsTRUE if the supplied object is anull Java reference.
Usage
.jnull(class = "java/lang/Object")is.jnull(x)Arguments
class | fully qualified target class name in JNI notation(e.g. |
x | object to check |
Details
.jnull is necessary ifnull is to be passed as anargument of.jcall or.jnew, in order to beable to find the correct method/constructor.
Example: given the following method definitions of the classA:
public static void run(String a);public static void run(Double n);
Calling.jcall("A",,"run",NULL) is ambiguous, because it isunclear which method is to be used. Therefore rJava requires classinformation with each argument to.jcall. If we wantedto run the String-version, we could use.jcall("A",,"run",.jnull("java/lang/String")).
is.jnull is a test that should be used to determine whether agiven Java reference is anull reference.
Value
.jnull returns a Java object reference (jobjRef) of anull object having the specified object class.
is.jnull returnsTRUE ifis.null(x) isTRUE or ifx is a Javanull reference.
See Also
Examples
## Not run: .jcall("java/lang/System","I","identityHashCode",.jnull())## End(Not run)Class "jobjRef" - Reference to a Java object
Description
This class describes a reference to an object held in a JavaVM.
Objects from the Class
Objects of this class should *not* be created directly. Instead, the function.jnew should be use to create new Java objects. They can also be created as results of the.jcall function.
Slots
jobj:Internal identifier of the object (external pointer to be precise)
jclass:Java class name of the object (in JNI notation)
Java-side attributes are not accessed via slots, but the$ operator instead.
Methods
This object's Java methods are not accessed directly. Instead,.jcall JNI-API should be used for invoking Java methods. For convenience the$ operator can be used to call methods via reflection API.
Author(s)
Simon Urbanek
See Also
.jnew,.jcall orjarrayRef-class
Initialize an R package containing Java code
Description
.jpackage initializes the Java Virtual Machine (JVM) for an Rpackage. In addition to starting the JVM it also registers Javaclasses and native code contained in the package with the JVM.function must be called before any rJava functions can be used.
Usage
.jpackage(name, jars='*', morePaths='', nativeLibrary=FALSE, lib.loc=NULL, parameters = getOption("java.parameters"), own.loader = FALSE)Arguments
name | name of the package. It should correspond to the |
jars | Java archives in the |
morePaths | vector listing any additional entries that shouldbe added to the class path. |
nativeLibrary | a logical determining whether rJava should lookfor native code in the R package's shared object or not. |
lib.loc | a character vector with path names of R libraries, or |
parameters | optional JVM initialization parameters which will beused if JVM is not initilized yet (see |
own.loader | if |
Details
.jpackage initializes a Java R package as follows: first theJVM is initialized via.jinit (if it is not runningalready). Then thejava directory of the package is added tothe class path. Then.jpackage prependsjars with thepath to thejava directory of the package and adds them to theclass path (or all.jar files if'*' was specified).Finally themorePaths parameter (if set) is passed to a callto.jaddClassPath.
Therefore the easiest way to create a Java package is to add.jpackage(pkgname, lib.loc=libname) in.onLoad or.First.lib, and copy all necessary classes to a JAR file(s)which is placed in theinst/java/ directory of the sourcepackage.
If a package needs special Java parameters,"java.parameters"option can be used to set them on initialization. Note, however, thatJava parameters can only be used during JVM initialization and otherpackage may have intialized JVM already.
Since rJava 0.9-14 there is support of package-specific classloaders using theown.loader=TRUE option. This is important forpackages that may be using classes that conflict with other packagesare therefore is highly recommended for new packages. Before thisfeature, there was only one global class loader which means that theclass path was shared for all class look ups. If two packagesuse the same (fully qualified) class name, even in a dependency, theyare likely to clash with each if they don't use exactly the sameversion. Therefore it is safer for each package use use a privateclass loader for its classes to guarantee that the only the classessupplied with the package will be used. To do that, a package will setown.loader=TRUE which instructs rJava to not change the globalloader, but instead create a separate one for the package and assignit to.rJava.class.loader in the package namespace. Then ifpackage wants to instantiate a new class, it would use.jnew("myClass", class.loader=.rJava.class.loader) to use itsown loader instead of the global one. The global loader's class pathwon't be touched, so it won't find the package's classes. It ispossible to get the loader used in a package using.jclassLoader(package="foo") which will return the global one ifthe package has not registered its own. Similarly, to retrieve theclass path used by a package, one would use.jclassPath(.jclassLoader(package="foo")).
Note that with the advent of multiple class loaders the value of thejava.class.path property is no longer meaningful as it canreflect only one of the loaders.
Value
The return value is an invisible TRUE if the initialization was successful.
See Also
Examples
## Not run: .onLoad <- function(libname, pkgname) { .jpackage(pkgname, lib.loc=libname, own.loader=TRUE) ## do not use, just an illustration of the concept: cat("my Java class path: ") print(.jclassPath(.jclassLoader(package=pkgname)))}## End(Not run)Rectangular java arrays
Description
References to java arrays that are guaranteed to be rectangular, i.e similarto R arrays
Objects from the Class
Objects of this class should *not* be created directly.Instead, they usually come as a result of a java method call.
Slots
jsig:JNI signature of the array type
jobj:Internal identifier of the object
jclass:Inherited from
jobjRef, but unspecifieddimension:dimension vector of the array
Extends
Class"jarrayRef", directly.Class"jobjRef", by class "jarrayRef", distance 2.
Methods
- length
signature(x = "jrectRef"): The number of elements in the array.Note that if the array has more than one dimension,it gives the number of arrays in the first dimension, and not the totalnumber of atomic objects in the array (like R does). This gives what would bereturned byarray.lengthin java.- str
signature(object = "jrectRef"): ...- [
signature(x = "jrectRef"): R indexing of rectangular java arrays- dim
signature(x = "jrectRef"): extracts the dimensions of the array- dim<-
signature(x = "jrectRef"): sets the dimensions of the array- unique
signature(x = "jrectRef"): unique objects in the array- duplicated
signature(x = "jrectRef"): seeduplicated- anyDuplicated
signature(x = "jrectRef"): seeanyDuplicated- sort
signature(x = "jrectRef"): returns anew array with elements from x in order- rev
signature(x = "jrectRef"): returns anew array with elements from x reversed- min
signature(x = "jrectRef"): the smallest object in the array (in the sense of the Comparable interface)- max
signature(x = "jrectRef"): the biggest object in the array (in the sense of the Comparable interface)- range
signature(x = "jrectRef"): the range of the array (in the sense of the Comparable interface)
Examples
v <- new( J("java.util.Vector") )v$add( "hello" )v$add( "world" )v$add( new( J("java.lang.Double"), "10.2" ) )array <- v$toArray()array[ c(TRUE,FALSE,TRUE) ]array[ 1:2 ]array[ -3 ]# lengthlength( array )# also works as a pseudo field as in javaarray$lengthSimple helper functions for Java reflection
Description
.jconstructors returns a character vector with all constructors fora given class or object..jmethods returns a character vector with all methods fora given class or object..jfields returns a character vector with all fields (aka attributes) for a given class or object.
Usage
.jconstructors(o, as.obj = FALSE, class.loader=.rJava.class.loader).jmethods(o, name = NULL, as.obj = FALSE, class.loader=.rJava.class.loader).jfields(o, name = NULL, as.obj = FALSE, class.loader=.rJava.class.loader)Arguments
o | Name of a class (either notation is fine) or an object whoseclass will be queried |
name | string, regular expression of the method/field to look for |
as.obj | if |
class.loader | optional, class loader to use for class look up ifneeded (i.e., if |
Details
There first two functions are intended to help with finding correctsignatures for methods and constructors. Since the low-level API inrJava doesn't use reflection automatically, it is necessary toprovide a proper signature. That is somewhat easier using the abovemethods.
Value
Returns a character vector (ifas.obj isFALSE) or alist of Java objects. Each entry corresponds to theConstructor resp.Method resp.Fieldobject. The string result is constructed by callingtoString() on the objects.
See Also
.jcall,.jnew,.jcast or$,jobjRef-method
Examples
## Not run: .jconstructors("java.util.Vector")v <- .jnew("java.util.Vector").jmethods(v, "add")## End(Not run)Java object serialization
Description
.jserialize serializes a Java object into raw vector usingJava serialization.
.junserialize re-constructs a Java object from its serialized(raw-vector) form.
.jcache updates, retrieves or removes R-side object cachewhich can be used for persistent storage of Java objects acrosssessions.
Usage
.jserialize(o).junserialize(data).jcache(o, update=TRUE)Arguments
o | Java object |
data | serialized Java object as a raw vector |
update | must be |
Details
Not all Java objects support serialization, see Java documentationfor details. Note that Java serialization and serialization of Robjects are two entirely different mechanisms that cannot beinterchanged..jserialize and.junserialize canbe used to access Java serialization facilities.
.jcache manipulates the R-side Java object cache associatedwith a given Java reference:
Java objects do not persist across sessions, because the JavaVirtual Machine (JVM) is destroyed when R is closed. All saved Javaobject references will be restored asnull references, sincethe corresponding objects no longer exist (see R documentation onserialization). However, it is possible to serialize a Java object(if supported by the object) and store its serialized form inR. This allows for the object to be deserialized when loaded intoanother active session (but see notes below!)
R-side cache consists of a serialized form of the object as rawvector. This cache is attached to the Java object and thus will besaved when the Java object is saved. rJava provides an automated wayof deserializing Java references if they arenull referencesand have a cache attached. This is done on-demand basis whenever areference to a Java object is required.
Therefore packages can use.jcache to provide a way ofcreating Java references that persist across sessions. However, theymust be very cautious in doing so. First, make sure the serializedform is not too big. Storing whole datasets in Java serialized formwill hog immense amounts of memory on the R side and should beavoided. In addition, be aware that the cache is just a snapshot, itdoesn't change when the referenced Java object is modified. Hence itis most useful only for references that are not modified outsideR. Finally, internal references to other Java objects accessiblefrom R are not retained (see below). Most common use of.jcache is with Java references that point to definitions ofmethods (e.g., models) and other descriptive objects which are thenused by other, active Java classes to act upon. Caching of suchactive objects is not a good idea, they should be instantiated byfunctions that operate on the descriptive references instead.
Important note: the serialization of Java references does NOTtake into account any dependencies on the R side. Therefore if youhold a reference to a Java object in R that is also referenced bythe serialized Java object on the Java side, then this relationshipcannot be retained upon restore. Instead, two copies of disjointobjects will be created which can cause confusion and erroneousbehavior.
The cache is attached to the reference external pointer and thus itis shared with all copies of the same reference (even when changedvia.jcast etc.), but it is independent of otherreferences to the object obtained separately(e.g., via.jcall or.jfield).
Also note that deserialization (even automated one) requires arunning virtual machine. Therefore you must make sure that either.jinit or.jpackage is used before anyJava references are accessed.
Value
.jserialize returns a raw vector
.junserialize returns a Java object orNULL if an erroroccurred (currently you may use.jcheck() to furtherinvestigate the error)
.jcache returns the current cache (usually a raw vector) orNULL if there is no cache.
Converts Java object to a simple scalar if possible
Description
.jsimplify attempts to convert Java objects that representsimple scalars into corresponding scalar representation in R.
Usage
.jsimplify(o, promote=FALSE)Arguments
o | arbitrary object |
promote | logical, if |
Details
Ifo is not a Java object reference,o is returnedas-is. Ifo is a reference to a scalar object (such as singleinteger, number, string or boolean) then the value of that object isreturned as R vector of the corresponding type and length one.
This function is used by.jfield to simplify the resultsof field access if required.
Currently there is no function inverse to this, the usual way to wrapscalar values in Java references is to use.jnew as thecorresponding constructor.
Value
Simple scalar oro unchanged.
See Also
Examples
## Not run: i <- .jnew("java/lang/Integer", as.integer(10))print(i)print(.jsimplify(i))## End(Not run)Java Class Loader
Description
.jaddClassPath adds directories or JAR files to the classpath.
.jclassPath returns a vector containing the current entries inthe class path
Usage
.jaddClassPath(path, class.loader=.rJava.class.loader).jclassPath(class.loader=.rJava.class.loader).jclassLoader(package=NULL)Arguments
path | character string vector listing the paths to add to theclass path |
class.loader | Java class loader to use for the query ofmadification. Defaults to global class loader. |
package | string, name of a package or |
Details
Whenever a class needs to be instantiated in Java it is referred byname which is used to locate a file with the bytecode for theclass. The mechanism to map a name to an actual bytecode to load indinstantiate is habdled by the Java class loader. It typically keeps alist of directories and JAR files to search for the class names.
The.jaddClassPath() function allows the user to append newlocations to the list of places which will be searched. The function.jclassPath retrieves the current sarch list from the loader.
When rJava is initialized, it instantiates the global class loaderwhich is responsible for finding classes in functions such as.jnew(). In addition to the global class loader, R packages cancreate their own class loaders to avoid conflicts between packagessuch that they can be sure to use their own files to look forclasses. See.jpackage for details on how that works.If thepackage argument is supplied.jclassLoader willlook in that package to see if it has a custom loader and will returnit, otherwise it returns the global loader. Note that is will fail withan error when supplied a non-existing package name.
If you want to trace issues related to missing classes, you can enabledebugging in the class loader by using thesetDebug method, forexample:.jclassLoader()$setDebug(1L)
Value
.jclassPath returns a character vector listing the class path sequence.
See Also
Examples
## Not run: .jaddClassPath("/my/jars/foo.jar","/my/classes/")print(.jclassPath())## End(Not run)Create a new Java object
Description
Creates a new Java object and invokes the constructor with given arguments.
Details
Thenew method is used as the high-level API to create newJava objects (for low-level access see.jnew). Itreturns the newly created Java object.
... arguments are passed to the constructor of the classspecified asJ("class.name").
Methods
newsignature(Class = "jclassName"): ...
See Also
Examples
## Not run: v <- new(J("java.lang.String"), "Hello World!")v$length()v$indexOf("World")names(v)## End(Not run)Internal functions and constants
Description
The following functions are either internal or are not officially partof the API and therefore may changes in the future.
Usage
.jaddLibrary(name, path, class.loader = .rJava.class.loader) .jclass(o, true = TRUE) .jclassRef(x, silent = FALSE) .jfindClass(cl, silent = FALSE, class.loader = .rJava.class.loader) .jfirst(libname, pkgname) .jidenticalRef(a, b) .jinherits(o, cl, class.loader = .rJava.class.loader) .jmergeClassPath(cp) .jmkref(jobj, jclass = "java/lang/Object") .joptions(...) .jproperty(key) .jrcall(o, method, ..., simplify = TRUE, class.loader = .rJava.class.loader) .jrmLibrary(name) .jsetJConvertor(java.class, fn) .jsetRConvertor(r.class, fn) .jstrVal(obj) .r2j(x, engine = NULL, convert = TRUE)Arguments
name | string, name of the library |
path | string, path |
class.loader | class loader object |
o | Java object |
x | Java object |
cl | string, class name (or Java class name object) |
libname | string, library location |
pkgname | string, package name |
a | Java object |
b | Java object |
cp | string, class path |
jobj | Java object |
simplify | logical |
java.class | string, class name |
fn | convertor function |
r.class | string, R class |
obj | Java object |
engine | Java engine object, if |
convert | logical |
... | additional parameters |
Creates java arrays by cloning
Description
Creates a java array by cloning a reference several times
Methods
- rep
signature(object = "jobjRef"): ...- rep
signature(object = "jarrayRef"): ...- rep
signature(object = "jrectRef"): ...
See Also
Examples
if (!nzchar(Sys.getenv("NOAWT"))) { p <- .jnew( "java.awt.Point" ) a <- rep( p, 10 ) stopifnot( dim(a) == c(10L ) ) a[[1]]$move( 10L, 50L ) stopifnot( a[[2]]$getX() == 0.0 )}Show a Java Object Reference
Description
Display a Java object reference in a descriptive, textual form. Thedefault implementation callstoString Java method to obtainobject's printable value and uses callsshow on the resultingstring garnished with additional details.
Methods
- show
signature(object = "jobjRef"): ...- show
signature(object = "jarrayRef"): ...- show
signature(object = "jclassName"): ...- str
signature(object = "jobjRef"): currently identical to show
Convert R objects to REXP references in Java
Description
toJava takes an R object and creates a reference to that objectin Java. This reference can then be passed to Java methods such thatthey can refer to it back in R. This is commonly used to pass functionsto Java such that Java code can call those functions later.
Usage
toJava(x, engine = NULL)Arguments
x | R object to reference. It can be any R object and it will beretained at least for the duration of the reference on the Java side. |
engine | REngine in which the reference is to be created. If<code>null</code> then the last created engine is used. This must bea Java object and a subclass of org.rosuda.REngine (and NOT the oldorg.rosuda.JRI.Rengine!). |
Value
There result is a Java reference (jobjRef) of the Java classREXPReference.
Examples
## Not run: .jinit() # requires JRI and REngine classes .jengine(TRUE) f <- function() { cat("Hello!\n"); 1 } fref <- toJava(f) # to use this in Java you would use something like: # public static REXP call(REXPReference fn) throws REngineException, REXPMismatchException { # return fn.getEngine().eval(new REXPLanguage(new RList(new REXP[] { fn })), null, false); # } # .jcall("Call","Lorg/rosuda/REngine/REXP;","call", fref) ## End(Not run)with and within methods for Java objects and class names
Description
Convenience wrapper that allow calling methods of Java object and classes from within the object (or class).
Usage
## S3 method for class 'jobjRef'with(data, expr, ...)## S3 method for class 'jobjRef'within(data, expr, ...)## S3 method for class 'jarrayRef'with(data, expr, ...)## S3 method for class 'jarrayRef'within(data, expr, ...)## S3 method for class 'jclassName'with(data, expr, ...)## S3 method for class 'jclassName'within(data, expr, ...)Arguments
data | A Java object reference or a java class name. See |
expr | R expression to evaluate |
... | ignored |
Details
The expression is evaluated in an environment that contains a mapping between the public fields and methods of the object.
The methods of the object are mapped to standard R functionsin the environment. In case of classes, only static methodsare used.
The fields of the object are mapped to active bindings(seemakeActiveBinding) so that they can be accessedand modified from within the environment. For classes, only static fields are used.
Value
with returns the value of the expression andwithin returns thedata argument
Author(s)
Romain Francois <francoisromain@free.fr>
References
thejava.lang.reflect package:https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/package-summary.html
Examples
if (!nzchar(Sys.getenv("NOAWT"))) { p <- .jnew( "java/awt/Point", 0L, 0L ) with( p, {# x and y and now 0move( 10L, 10L )# x and y are now 10x <- x + y } ) f <- within( .jnew( "javax/swing/JFrame" ) , {layout <- .jnew( "java/awt/BorderLayout" )setLayout( layout )add( .jnew( "javax/swing/JLabel", "north" ), layout$NORTH )add( .jnew( "javax/swing/JLabel", "south" ), layout$SOUTH )add( .jnew( "javax/swing/JLabel", "west" ), layout$WEST )add( .jnew( "javax/swing/JLabel", "east" ), layout$EAST )setSize( .jnew( "java/awt/Dimension", 400L, 400L ) )setVisible( TRUE ) } )}Double <- J("java.lang.Double")with( Double, MIN_VALUE )with( Double, parseDouble( "10.2" ) )## Not run: # inner class exampleHashMap <- J("java.util.HashMap")with( HashMap, new( SimpleEntry, "key", "value" ) )with( HashMap, SimpleEntry )## End(Not run)with( J("java.lang.System"), getProperty("java.home") )