{"id":13748245,"url":"https://github.com/joeferner/node-java","last_synced_at":"2025-05-14T08:05:17.310Z","repository":{"id":2272090,"uuid":"3228734","full_name":"joeferner/node-java","owner":"joeferner","description":"Bridge API to connect with existing Java APIs.","archived":false,"fork":false,"pushed_at":"2025-05-01T11:36:30.000Z","size":20374,"stargazers_count":1885,"open_issues_count":223,"forks_count":288,"subscribers_count":69,"default_branch":"master","last_synced_at":"2025-05-07T07:18:04.892Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/joeferner.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2012-01-20T18:55:49.000Z","updated_at":"2025-05-01T11:36:29.000Z","dependencies_parsed_at":"2022-09-01T02:01:37.777Z","dependency_job_id":"fad39e49-7394-4942-966b-2e6468d2c77b","html_url":"https://github.com/joeferner/node-java","commit_stats":{"total_commits":509,"total_committers":64,"mean_commits":7.953125,"dds":"0.41257367387033395","last_synced_commit":"6c48aacd3705b5c3e1cb67d82f84b964ee7f7652"},"previous_names":[],"tags_count":57,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeferner%2Fnode-java","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeferner%2Fnode-java/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeferner%2Fnode-java/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeferner%2Fnode-java/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/joeferner","download_url":"https://codeload.github.com/joeferner/node-java/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253331066,"owners_count":21891855,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T07:00:37.654Z","updated_at":"2025-05-14T08:05:17.288Z","avatar_url":"https://github.com/joeferner.png","language":"C++","funding_links":[],"categories":["C++","others"],"sub_categories":[],"readme":"\n\n[![master](https://github.com/joeferner/node-java/actions/workflows/master.yml/badge.svg)](https://github.com/joeferner/node-java/actions/workflows/master.yml)\n\nBridge API to connect with existing Java APIs.\n\n[Google Groups Discussion Forum](https://groups.google.com/forum/#!forum/node-java)\n\n### Other projects that might be helpful\n\n* [node-java-maven](https://github.com/joeferner/node-java-maven) - manages your node-java classpath by using maven dependency management.\n\n## Installation\n\n```bash\n$ npm install java\n```\n\nNotes:\n\n* node-gyp requires python 2.x not python 3.x. See https://github.com/TooTallNate/node-gyp/issues/155 for more details.\n* If you see an error such as \"Call to 'node findJavaHome.js' returned exit status 1\"\n      Try running `node findJavaHome.js` in the node-java directory to see the full failure message.\n* If you are having problems finding 'jni.h'. Make sure you have the JDK installed not just the JRE. If you are using\n      OpenJDK you want the openjdk-7-jdk package, not openjdk-7-jre.  _Mavericks users see [Issue #86](https://github.com/nearinfinity/node-java/issues/86) if you run into this._\n\n### Installation Ubuntu\n\n- `sudo apt install make g++`\n- If u've error (on global installation): `EACCES user nobody does not have permission to access the dev dir /root/.cache/node-gyp/10.16.0`, then just run: `npm i -g java --unsafe-perm`\n\n### Installation OSX\n\n* If you run into strange runtime issues, it could be because the Oracle JDK does not advertise itself as available for JNI.  See [Issue 90](https://github.com/joeferner/node-java/issues/90#issuecomment-45613235) for more details and manual workarounds.  If this does occur for you, please update the issue.\n\n### Installation Windows\n\nFor 64 bit installs with 32 bit node:\n* you need the 32 bit JDK, with the 64 bit JDK you will see LNK2001 errormessages (http://stackoverflow.com/questions/10309304/what-library-to-link-to-on-windows-7-for-jni-createjavavm).\n* when using the windows SDK 7.1 command prompt (64 bits) be sure to setenv.cmd /Release /x86\n\nIf you get `ENOENT` errors looking for `\u003cnodepath\u003e\\node_modules\\node-gyp\\..`, ensure you have node-gyp installed as a global nodule:\n\n```bash\nnpm install -g node-gyp\n```\n\nIf you get `D9025` warnings and `C1083` errors when looking for `.sln` or `.h` files, be sure you've got the `node-gyp`'s dependencies, [as explained here](https://github.com/joeferner/node-java#installation).\n\nAlternatively, Windows users can easily install all required tools by running the following command in PowerShell as administrator. For more information see [windows-build-tools project page](https://github.com/felixrieseberg/windows-build-tools):\n\n```sh\nnpm install --global --production windows-build-tools\n```\n\n### Installation ARM (Raspberry Pi)\n\n```bash\nGYP_DEFINES=\"armv7=0\" CCFLAGS='-march=armv6' CXXFLAGS='-march=armv6' npm install java\n```\n\n## Manual compile (Using node-gyp)\n\n```bash\n./compile-java-code.sh\nnode-gyp configure build\nnpm test\n```\n\n_NOTE: You will need node-gyp installed using \"npm install -g node-gyp\"_\n\nOn Raspian you might need a: \n\n* sudo ln -s /usr/lib/jvm/jdk-7-oracle-arm-vfp-hflt /opt/jdk\n\nSome issues with the OpenSDK7 so take the Oracle version for compiling.\n\n## Docker\n\nIf you want to play with node-java but don't want to setup the build environment you can run it in docker.\n\n```\ndocker run -it joeferner/node-java bash\n```\n\nThen inside the docker container create a directory and run\n\n```bash\nnpm install --unsafe-perm java\n```\n\nThen create a file called `test.js` with the following contents\n\n```\nvar java = require('java');\nvar javaLangSystem = java.import('java.lang.System');\n\njavaLangSystem.out.printlnSync('Hello World');\n```\n\nThen run\n\n```bash\nnode test.js\n```\n\n### Java 1.8 support\n\nManual compilation for Java 1.8 support requires additional steps:\n\n```bash\n./compile-java-code.sh\n./compile-java8-code.sh\nnode-gyp configure build\nnpm test\n```\n\nJava 1.8 language features can be used in Java classes only if a Java 1.8 JRE is available. The script compile-java8-code.sh is used only to compile java classes used in the 'test8' unit tests, but these classes are checked into the test8/ directory. Note that unit tests in the test8/ directory will pass (by design) if run against a Java 1.7 JRE, provided that a java.lang.UnsupportedClassVersionError is caught with the message 'Unsupported major.minor version 52.0' (the expected behavior when Java 1.8 language features are used in an older JRE).\n\n## Installation node-webkit\n\n```bash\nnpm install -g nw-gyp\nnpm install java\ncd node_modules/java\nnw-gyp configure --target=0.10.5\nnw-gyp build\n```\n\n_See testIntegration/webkit for a working example_\n\n## Using node-java in existing maven projects\n\nWhen using node-java in existing maven projects, all the dependencies and the class files of the project have to be pushed to the classpath.\n\nOne possible solution would be:\n\nIssue the command:\n\n\u003e mvn dependency:copy-dependencies\n\nThen create the following module javaInit:\n\n```javascript\n\"use strict\";\nvar fs = require(\"fs\");\nvar java = require(\"java\");\nvar baseDir = \"./target/dependency\";\nvar dependencies = fs.readdirSync(baseDir);\n\ndependencies.forEach(function(dependency){\n    java.classpath.push(baseDir + \"/\" + dependency);\n})\n\njava.classpath.push(\"./target/classes\");\njava.classpath.push(\"./target/test-classes\");\n\nexports.getJavaInstance = function() {\n    return java;\n}\n```\n\nand then in the consuming class write:\n\n```javascript\n\nvar javaInit = require('./javaInit');\nvar java = javaInit.getJavaInstance();\n\n//your code goes here\n```\n\n\n\n## Quick Examples\n\n```javascript\nvar java = require(\"java\");\njava.classpath.push(\"commons-lang3-3.1.jar\");\njava.classpath.push(\"commons-io.jar\");\n\nvar list1 = java.newInstanceSync(\"java.util.ArrayList\");\nconsole.log(list1.sizeSync()); // 0\nlist1.addSync('item1');\nconsole.log(list1.sizeSync()); // 1\n\njava.newInstance(\"java.util.ArrayList\", function(err, list2) {\n  list2.addSync(\"item1\");\n  list2.addSync(\"item2\");\n  console.log(list2.toStringSync()); // [item1, item2]\n});\n\nvar ArrayList = java.import('java.util.ArrayList');\nvar list3 = new ArrayList();\nlist3.addSync('item1');\nlist3.equalsSync(list1); // true\n```\n\n### Create a char array\n\n```javascript\nvar charArray = java.newArray(\"char\", \"hello world\\n\".split(''));\n```\n\n### Create a byte array\n\n```javascript\nvar byteArray = java.newArray(\n  \"byte\",\n  \"hello world\\n\"\n    .split('')\n    .map(function(c) { return java.newByte(String.prototype.charCodeAt(c)); }));\n```\n\n### Using java.lang.Long and long\n\nJavaScript only supports 32-bit integers. Because of this java longs must be treated specially.\nWhen getting a long result the value may be truncated. If you need the original value there is\na property off of the result called \"longValue\" which contains the un-truncated value as a string.\nIf you are calling a method that takes a long you must create it using [java.newInstance](#javaNewInstance).\n\n```javascript\nvar javaLong = java.newInstanceSync(\"java.lang.Long\", 5);\nconsole.log('Possibly truncated long value: ' + javaLong);\nconsole.log('Original long value (as a string): ' + javaLong.longValue);\njava.callStaticMethodSync(\"Test\", \"staticMethodThatTakesALong\", javaLong);\n```\n\n### Exceptions\n\nExceptions from calling methods either caught using JavaScript try/catch block or passed\nto a callback as the first parameter may have a property named \"cause\" which has a reference\nto the Java Exception object which caused the error.\n\n```javascript\ntry {\n  java.methodThatThrowsExceptionSync();\n} catch(ex) {\n  console.log(ex.cause.getMessageSync());\n}\n```\n\n\u003ca name=\"asyncOptionsDetails\" \u003e\n\n### AsyncOptions: control over the generation of sync, async \u0026 promise method variants.\n\nAs of release 0.4.5 it became possible to create async methods that return promises by setting the `asyncOptions` property of the java object. With release 0.4.7 this feature is extended to allow changing the suffix assigned for sync and async method variants, and to further configure this module to optionally omit generation of any of these variants.\n\nExample:\n\n```javascript\nvar java = require(\"java\");\njava.asyncOptions = {\n  asyncSuffix: undefined,     // Don't generate node-style methods taking callbacks\n  syncSuffix: \"\",              // Sync methods use the base name(!!)\n  promiseSuffix: \"Promise\",   // Generate methods returning promises, using the suffix Promise.\n  promisify: require('util').promisify // Needs Node.js version 8 or greater, see comment below\n};\njava.classpath.push(\"commons-lang3-3.1.jar\");\njava.classpath.push(\"commons-io.jar\");\n\njava.import(\"java.util.ArrayList\"); // see NOTE below\n\njava.newInstancePromise(\"java.util.ArrayList\")\n    .then(function(list) { return list.addPromise(\"item1\"); })\n    .then(function(list) { return list.addPromise(\"item2\"); })\n    .catch(function(err) { /* handle error */ });\n```\n\n#### NOTES:\n\n* If you want the defacto standard behavior, simply don't set java.asyncOptions.\n* If you do provide asyncOptions, be aware that this module will not generate method variants of a given flavor if you don't provide a string value for the corresponding suffix (`asyncSuffix`, `syncSuffix`, `promiseSuffix`). In the example above, the application is configured to omit the method variants using node-style async callback functions.\n* If you provide `asyncOptions.promiseSuffix` then you must also set `asyncOptions.promisify` to a function that *promisifies* a node-style async function. I.e. the provided function must take as input a function whose last argument is a node callback function, and it must return an equivalent promise-returning function. Several Promises/A+ libraries provide such functions, but it may be necessary to provide a wrapper function. See `testHelpers.js` for an example.\n* For `promisify` implementation, if you are using Node.js version 8.0.0 or newer then `promisify: require('util').promisify` will work out of the box. If you need to support and older Node.js version then an implementation needs to be provided, for example, `promisify: require(\"when/node\").lift`\n* If you provide `asyncOptions.promisify` then you must provide a *non-empty* string for `asyncOptions.promiseSuffix`.\n* Either (but not both) `asyncSuffix` or `syncSuffix` can be the empty string. If you want the defacto standard behavior for no suffix on async methods, you must provide an empty string for `asyncSuffix`.\n* We've tested promises with five Promises/A+ implementations. See `testHelpers.js` for more information.\n* NOTE: Due to specifics of initialization order, the methods  `java.newInstancePromise`, `java.callMethodPromise`, and `java.callStaticMethodPromise` are not available until the JVM has been created. You may need to call some other java method such as `java.import()` to finalize java initialization, or even better, the function `java.ensureJvm()`.\n\n##### Special note about the exported module functions `newInstance`, `callMethod`, and `callStaticMethod`.\nThese methods come in both async and sync variants. If you provide the `promisify` and `promiseSuffix` attributes in asyncOptions then you'll also get the Promises/A+ variant for these three functions. However, if you change the defacto conventions for the `syncSuffix` (i.e. 'Sync') and/or `asyncSuffix` (i.e. '') it will not affect the naming for these three functions. I.e. no matter what you specify in asyncOptions, the async variants are named `newInstance`, `callMethod`, and `callStaticMethod`, and the sync variants are named `newInstanceSync`, `callMethodSync`, and `callStaticMethodSync`.\n\n## Varargs support\n\nWith v0.5.0 node-java now supports methods with variadic arguments (varargs). Prior to v0.5.0, a JavaScript call to a Java varargs method had to construct an array of the variadic arguments using `java.newArray()`. With v0.5.0 JavaScript applications can simply use the variadic style.\n\nIn most cases it is still acceptable to use `java.newArray()`. But it is now possible to pass a plain JavaScript array, or use the variadic style. For example, consider these snippets from the unit test file `test/varargs-test.js`:\n\n```\n    test.equal(Test.staticVarargsSync(5, 'a', 'b', 'c'), '5abc');\n    test.equal(Test.staticVarargsSync(5, ['a', 'b', 'c']), '5abc');\n    test.equal(Test.staticVarargsSync(5, java.newArray('java.lang.String', ['a', 'b', 'c'])), '5abc');\n\n```\n\nNote that when passing a JavaScript array (e.g. `['a', 'b', 'c']`) for a varargs parameter, node-java must infer the Java type of the array. If all of the elements are of the same JavaScript primitive type (`string` in this example) then node-java will create a Java array of the corresponding type (e.g. `java.lang.String`). The Java types that node-java can infer are: `java.lang.String`, `java.lang.Boolean`, `java.lang.Integer`, `java.lang.Long`, and `java.lang.Double`. If an array has a mix of `Integer`, `Long`, and `Double`, then the inferred type will be `java.lang.Number`. Any other mix will result in an inferred type of `java.lang.Object`.\n\nMethods accepting varargs of a generic type are also problematic. You will need to fall back to using `java.newArray()`. See [Issue #285](https://github.com/joeferner/node-java/issues/285).\n\n## JVM Creation\n\nWith v0.5.1 a new API is available to make it easier for a complex application to have full control over JVM creation. In particular, it is now easier to compose an application from several modules, each of which must add to the Java classpath and possibly do other operations just before or just after the JVM has been created. See the methods [ensureJvm](#javaEnsureJvm) and [registerClient](#javaRegisterClient). See also several of the tests in the testAsyncOptions directory.\n\n# Release Notes\n\n### v0.5.0\n\n* Support for varargs. This change is not 100% backwards compatible, but the fix is generally easy and results in more natural code.\n\n### v0.2.0\n\n* java.lang.Long and long primitives are handled better. See\n  \\([Issue #37](https://github.com/nearinfinity/node-java/issues/37)\\) and\n  \\([Issue #40](https://github.com/nearinfinity/node-java/issues/40)\\).\n\n# Index\n\n## java\n * [classpath](#javaClasspath)\n * [options](#javaOptions)\n * [asyncOptions](#javaAsyncOptions)\n * [import](#javaImport)\n * [newInstance](#javaNewInstance)\n * [instanceOf](#javaInstanceOf)\n * [callStaticMethod](#javaCallStaticMethod)\n * [callMethod](#javaCallMethod)\n * [getStaticFieldValue](#javaGetStaticFieldValue)\n * [setStaticFieldValue](#javaSetStaticFieldValue)\n * [newArray](#javaNewArray)\n * [newByte](#javaNewByte)\n * [newShort](#javaNewShort)\n * [newLong](#javaNewLong)\n * [newChar](#javaNewChar)\n * [newDouble](#javaNewDouble)\n * [newFloat](#javaNewFloat)\n * [newProxy](#javaNewProxy)\n * [isJvmCreated](#javaIsJvmCreated)\n * [registerClient](#javaRegisterClient)\n * [registerClientP](#javaRegisterClientP)\n * [ensureJvm](#javaEnsureJvm)\n\n## java objects\n * [Call Method](#javaObjectCallMethod)\n * [Get/Set Field](#javaObjectGetSetField)\n\n# API Documentation\n\n\u003ca name=\"java\"\u003e\n\n# java\n\n\u003ca name=\"javaClasspath\" \u003e\n\n## classpath\n\n*java.classpath**\n\nArray of paths or jars to pass to the creation of the JVM.\n\nAll items must be added to the classpath before calling any other node-java methods.\n\n__Example__\n\n    java.classpath.push('commons.io.jar');\n    java.classpath.push('src');\n\n## options\n\n\u003ca name=\"javaOptions\" \u003e\n\n*java.options**\n\nArray of options to pass to the creation of the JVM.\n\nAll items must be added to the options before calling any other node-java methods.\n\n__Example__\n\n    java.options.push('-Djava.awt.headless=true');\n    java.options.push('-Xmx1024m');\n\n## asyncOptions\n\n```javascript\njava.asyncOptions = {\n  asyncSuffix: undefined,     // Don't generate node-style methods taking callbacks\n  syncSuffix: \"\",              // Sync methods use the base name(!!)\n  promiseSuffix: \"Promise\",   // Generate methods returning promises, using the suffix Promise.\n  promisify: require('util').promisify // Needs Node.js version 8 or greater, see comment below\n  ifReadOnlySuffix: \"_alt\"\n};\n```\n\n * `asyncSuffix` Suffix for callback-based async method call signatures.\n * `syncSuffix` Suffix for synchronous method call signatures.\n * `promiseSuffix` Suffix for promise-based async method call signatures\n * `promisify` Callback-to-promise transform implementation. From Node.js version 8 one can just use Node.js implementation: `promisify: require('util').promisify`.\n * `ifReadOnlySuffix` See [Static Member Name Conflicts](#staticMemberNameConflicts).\n\nSee [Async Options](#asyncOptionsDetails) for details. \n\n## import\n\n\u003ca name=\"javaImport\" \u003e\n\n*java.import(className)**\n\nLoads the class given by className such that it acts and feels like a JavaScript object.\n\n__Arguments__\n\n * className - The name of the class to create. Separate nested classes using `'$'` (eg. `com.nearinfinty.MyClass$NestedClass`).\n\n__Example__\n\n    var Test = java.import('Test');\n    Test.someStaticMethodSync(5);\n    console.log(Test.someStaticField);\n\n    var value1 = Test.NestedEnum.Value1;\n\n    var test = new Test();\n    list.instanceMethodSync('item1');\n\n## newInstance\n\n\u003ca name=\"javaNewInstance\" \u003e\n\n*java.newInstance(className, [args...], callback)**\n\n**java.newInstanceSync(className, [args...]) : result**\n\nCreates an instance of the specified class. If you are using the sync method an exception will be throw if an error occurs,\notherwise it will be the first argument in the callback.\n\n__Arguments__\n\n * className - The name of the class to create. Separate nested classes using `'$'` (eg. `com.nearinfinty.MyClass$NestedClass`).\n * callback(err, item) - Callback to be called when the class is created.\n\n__Example__\n\n    var list = java.newInstanceSync(\"java.util.ArrayList\");\n\n    java.newInstance(\"java.util.ArrayList\", function(err, list) {\n      if(err) { console.error(err); return; }\n      // new list\n    });\n\n## instanceOf\n\n\u003ca name=\"javaInstanceOf\" \u003e\n\n*java.instanceOf(javaObject, className)**\n\nDetermines of a javaObject is an instance of a class.\n\n__Arguments__\n\n * javaObject - Instance of a java object returned from a method or from newInstance.\n * className - A string class name.\n\n__Example__\n\n    var obj = java.newInstanceSync(\"my.package.SubClass\");\n\n    if(java.instanceOf(obj, \"my.package.SuperClass\")) {\n      console.log(\"obj is an instance of SuperClass\");\n    }\n\n## callStaticMethod\n\n\u003ca name=\"javaCallStaticMethod\" \u003e\n\n*java.callStaticMethod(className, methodName, [args...], callback)**\n\n**java.callStaticMethodSync(className, methodName, [args...]) : result**\n\nCalls a static method on the specified class. If you are using the sync method an exception will be throw if an error occurs,\notherwise it will be the first argument in the callback.\n\n__Arguments__\n\n * className - The name of the class to call the method on. Separate nested classes using `'$'` (eg. `com.nearinfinty.MyClass$NestedClass`).\n * methodName - The name of the method to call. The method name can include the full signature (see [Getting the full method signature](#getFullMethodSignature)).\n * callback(err, item) - Callback to be called when the class is created.\n\n__Example__\n\n    var result = java.callStaticMethodSync(\"com.nearinfinty.MyClass\", \"doSomething\", 42, \"test\");\n\n    java.callStaticMethod(\"com.nearinfinty.MyClass\", \"doSomething\", 42, \"test\", function(err, results) {\n      if(err) { console.error(err); return; }\n      // results from doSomething\n    });\n\n## callMethod\n\n\u003ca name=\"javaCallMethod\" \u003e\n\n*java.callMethod(instance, methodName, [args...], callback)**\n\n**java.callMethodSync(instance, methodName, [args...]) : result**\n\nCalls a method on the specified instance. If you are using the sync method an exception will be throw if an error occurs,\notherwise it will be the first argument in the callback.\n\n__Arguments__\n\n * instance - An instance of the class from newInstance.\n * methodName - The name of the method to call. The method name can include the full signature (see [Getting the full method signature](#getFullMethodSignature)).\n * callback(err, item) - Callback to be called when the class is created.\n\n__Example__\n\n    var instance = java.newInstanceSync(\"com.nearinfinty.MyClass\");\n\n    var result = java.callMethodSync(\"com.nearinfinty.MyClass\", \"doSomething\", 42, \"test\");\n\n    java.callMethodSync(instance, \"doSomething\", 42, \"test\", function(err, results) {\n      if(err) { console.error(err); return; }\n      // results from doSomething\n    });\n\n## getStaticFieldValue\n\n\u003ca name=\"javaGetStaticFieldValue\" \u003e\n\n*java.getStaticFieldValue(className, fieldName)**\n\nGets a static field value from the specified class.\n\n__Arguments__\n\n * className - The name of the class to get the value from. Separate nested classes using `'$'` (eg. `com.nearinfinty.MyClass$NestedClass`).\n * fieldName - The name of the field to get the value from.\n\n__Example__\n\n    var data = java.getStaticFieldValue(\"com.nearinfinty.MyClass\", \"data\");\n\n## setStaticFieldValue\n\n\u003ca name=\"javaSetStaticFieldValue\" \u003e\n\n*java.setStaticFieldValue(className, fieldName, newValue)**\n\nSets a static field value on the specified class.\n\n__Arguments__\n\n * className - The name of the class to set the value on. Separate nested classes using `'$'` (eg. `com.nearinfinty.MyClass$NestedClass`).\n * fieldName - The name of the field to set the value on.\n * newValue - The new value to assign to the field.\n\n__Example__\n\n    java.setStaticFieldValue(\"com.nearinfinty.MyClass\", \"data\", \"Hello World\");\n\n## newArray\n\n\u003ca name=\"javaNewArray\" \u003e\n\n*java.newArray(className, values[])**\n\nCreates a new java array of given glass type. To create array of primitive types like `char`, `byte`, etc, pass the primitive type name (eg.  `java.newArray(\"char\", \"hello world\\n\".split(''))`). \n\n__Arguments__\n\n * className - The name of the type of array elements. Separate nested classes using `'$'` (eg. `com.nearinfinty.MyClass$NestedClass`).\n * values - A JavaScript array of values to assign to the java array.\n\n__Example__\n\n    var newArray = java.newArray(\"java.lang.String\", [\"item1\", \"item2\", \"item3\"]);\n\n## newByte\n\n\u003ca name=\"javaNewByte\" \u003e\n\n*java.newByte(val)**\n\nCreates a new java byte. This is needed because JavaScript does not have the concept of a byte.\n\n__Arguments__\n\n * val - The value of the java byte.\n\n__Example__\n\n    var b = java.newByte(12);\n\n## newShort\n\n\u003ca name=\"javaNewShort\" \u003e\n\n*java.newShort(val)**\n\nCreates a new java short. This is needed because JavaScript does not have the concept of a short.\n\n__Arguments__\n\n * val - The value of the java short.\n\n__Example__\n\n    var s = java.newShort(12);\n\n## newLong\n\n\u003ca name=\"javaNewLong\" \u003e\n\n*java.newLong(val)**\n\nCreates a new java long. This is needed because JavaScript does not have the concept of a long.\n\n__Arguments__\n\n * val - The value of the java long.\n\n__Example__\n\n    var s = java.newLong(12);\n\n## newChar\n\n\u003ca name=\"javaNewChar\" \u003e\n\n*java.newChar(val)**\n\nCreates a new java char. This is needed because JavaScript does not have the concept of a char.\n\n__Arguments__\n\n * val - The value of the java char.\n\n__Example__\n\n    var ch = java.newChar('a');\n\n## newDouble\n\n\u003ca name=\"javaNewDouble\" \u003e\n\n*java.newDouble(val)**\n\nCreates a new java double. This is needed to force JavaScript's number to a double to call some methods.\n\n__Arguments__\n\n * val - The value of the java double.\n\n__Example__\n\n    var d = java.newDouble(3.14);\n\n## newFloat\n\n\u003ca name=\"javaNewFloat\" \u003e\n\n*java.newFloat(val)**\n\nCreates a new java float. This is needed to force JavaScript's number to a float to call some methods.\n\n__Arguments__\n\n * val - The value of the java float.\n\n__Example__\n\n    var f = java.newFloat(3.14);\n\n## newProxy\n\n\u003ca name=\"javaNewProxy\" \u003e\n\n*java.newProxy(interfaceName, functions)**\n\nCreates a new java Proxy for the given interface. Functions passed in will run on the v8 main thread and not a new thread.\n\nThe returned object has a method unref() which you can use to free the object for\ngarbage collection.\n\n__Arguments__\n\n * interfaceName - The name of the interface to proxy. Separate nested classes using `'$'` (eg. `com.nearinfinty.MyClass$NestedClass`).\n * functions - A hash of functions matching the function in the interface.\n\n__Example__\n\n    var myProxy = java.newProxy('java.lang.Runnable', {\n      run: function () {\n        // This is actually run on the v8 thread and not the new java thread\n        console.log(\"hello from thread\");\n      }\n    });\n\n    var thread = java.newInstanceSync(\"java.lang.Thread\", myProxy);\n    thread.start();\n\n## isJvmCreated \n\n\u003ca name=\"javaisJvmCreated\" \u003e\n\n*java.isJvmCreated()**\n\nReturns true if the JVM has been created. The JVM can only be created once.\n\n## registerClient\n\n\u003ca name=\"javaRegisterClient\" \u003e\n\n*java.registerClient(before, after)**\n\nRegister that a client wants to be called back immediately before and/or immediately after the JVM is created. If used, this function must be called before the JVM has been created. The before function is typically used to add to the classpath. The function may execute asynchronous operations (such as a async glob function). The after function is sometimes useful for doing one-time initialization that requires the JVM to first be initialized. If either function is unnecessary, use `null` or `undefined`. See also `registerClientP` and `ensureJvm`. See the unit tests in `testAsyncOptions` for examples.\n\n## registerClientP\n\n\u003ca name=\"javaRegisterClientP\" \u003e\n\n*java.registerClientP(before, after)**\n\nLike java.registerClient, but before and after are assumed to be functions returning promises.\n\n## ensureJvm\n\n\u003ca name=\"javaEnsureJvm\" \u003e\n\n*java.ensureJvm(callback)**\n\nIf the JVM has not yet been created, execute the full JVM initialization process, then call callback function when initialization is complete. If the JVM has been created, just call the callback. Note that the full initialization process includes: 1) executing all registered client *before* hooks, 2) creating the JVM, then 3) executing all registered client *after* hooks.\n\n\n\n\u003ca name=\"javaObject\"\u003e\n\n# `java` object\n\n## Call Method\n\n\u003ca name=\"javaObjectCallMethod\" \u003e\n\n*obj._methodName_([args...], callback)**\n\n**obj._methodNameSync_([args...]) : result**\n\nOnce you have a java object either by creating a new instance or as a result of a method call you can then call methods on that object.\nAll public, non-static methods are exposed in synchronous and asynchronous flavors.\n\n__Arguments__\n\n * args - The arguments to pass to the method.\n * callback(err, item) - Callback to be called when the method has completed.\n\n__Example__\n\n    var list = java.newInstanceSync(\"java.util.ArrayList\");\n    list.addSync(\"item1\");\n    list.add(\"item2\", function(err, result) {\n      if(err) { console.error(err); return; }\n    });\n\n## Field Access\n\n\u003ca name=\"javaObjectGetSetField\" \u003e\n\n*obj._fieldName_ = val**\n\n**val = obj._fieldName_**\n\nOnce you have a java object either by creating a new instance or as a result of a method call you can get instance\nfield values.\n\n__Example__\n\n    var list = java.newInstanceSync(\"com.nearinfinty.MyClass\");\n    list.data = \"test\";\n    var data = list.data;\n\n## Getting the Full Method Signature\n\n\u003ca name=\"getFullMethodSignature\" \u003e\n\nRun `javap -s -classpath \u003cyour-class-path\u003e \u003cyour-class-name\u003e`. Find the method name you are looking for. For example:\n\n```\npublic int methodAmbiguous(java.lang.Double);\n  Signature: (Ljava/lang/Double;)I\n```\n\nThe full method signature would be `methodAmbiguous(Ljava/lang/Double;)I`.\n\nIf you have grep, a shortcut is `javap -s -classpath . my.company.MyClass | grep -A1 myMethodName`.\n\n# Signal Handling\n\nThe JVM intercepts signals (Ctrl+C, etc.) before node/v8 gets to handle them. To fix this there are a couple options.\n\n## Signal Handling Option 1\n\nOne option to capture these events is to add the following flag:\n\n```javascript\njava.options.push('-Xrs');\n```\n\nAs `man java` says, the `-Xrs` flag will “reduce usage of operating-system signals by [the] Java virtual machine (JVM)”, to avoid issues when developing “applications that embed the JVM”.\n\n## Signal Handling Option 2\n\nHook into the runtime shutdown hook.\n\nFirst create a java wrapper around the Runtime.addShutdownHook method to allow using a proxy object.\n\n```java\npublic class ShutdownHookHelper {\n  public static void setShutdownHook(final Runnable r) {\n    Runtime.getRuntime().addShutdownHook(new Thread() {\n      @Override\n      public void run() {\n        r.run();\n      }\n    });\n  }\n}\n```\n\nCompile ShutdownHookHelper and then use it as follows.\n\n```javascript\nvar java = require('./');\njava.classpath.push('.');\nvar ShutdownHookHelper = java.import('ShutdownHookHelper');\n\nShutdownHookHelper.setShutdownHookSync(java.newProxy('java.lang.Runnable', {\n  run: function () {\n    console.log(\"do shutdown stuff here instead.\");\n  }\n}));\n```\n\n# Object lifetime\n\nWhen you call a Java method through node-java, any arguments (V8/JavaScript objects) will be converted to Java objects  on the v8 main thread via a call to v8ToJava (found in utils.cpp). The JavaScript object is not held on to and can be garbage collected by v8. If this is an async call, the reference count on the Java objects will be incremented. The Java method will be invoked in a node.js async thread (see uv_queue_work). When the method returns, the resulting object will be returned to the main v8 thread and converted to JavaScript objects via a call to javaToV8 and the Java object's reference count will then be decremented to allow for garbage collection. The resulting v8 object will then be returned to the callers callback function.\n\n\n\u003ca name=\"staticMemberNameConflicts\" \u003e\n\n# Static member name conflicts ('name', 'arguments', 'caller')\n\nThe JavaScript object returned by `java.import(classname)` is a JavaScript constructor Function, implemented such that you can create instances of the Java class. For example:\n\n```javascript\nvar Test = java.import('Test');\nvar test = new Test();\n\nTest.someStaticMethod(function(err, result) { ... });\n\nvar value1 = Test.NestedEnum.Value1;\n```\n\nBut JavaScript reserves a few property names of Function objects: `name`, `arguments`, and `caller`. If your class has public static members (either methods or fields) with these names, node-java is unable to create the necessary property to implement the class's API. For example, suppose your class `Test` implements a static method named `caller`, or has a `NestedEnum` with a value `name`:\n\n```java\npublic class Test {\n    ...\n    public static String caller() { return \"something\"; }\n    public enum NestedEnum { foo, name };\n}\n```\n\nIn JavaScript, you would expect to be able to use those static members like this:\n\n```javascript\nvar Test = java.import('Test');\nTest.caller(function(err, result) { ... });  // ERROR\nvar value = Test.NestedEnum.name;  // ERROR\n```\n\nNode-java can't create those properties, so the above code won't work. Instead, node-java appends a suffix to the name. The default suffix is simply an underscore `_`, but you can change the suffix using `asyncOptions`:\n\n```javascript\nvar java = require('java');\n\njava.asyncOptions = {\n  asyncSuffix: \"\",\n  syncSuffix: \"Sync\",\n  ifReadOnlySuffix: \"_alt\"\n};\n\nvar Test = java.import('Test');\nTest.caller_alt(function(err, result) { ... });  // OK\nvar value = Test.NestedEnum.name_alt;  // OK\n```\n\n# Troubleshooting\n\n## Error: Cannot find module '../build/jvm_dll_path.json'\n\nEither `postInstall.js` didn't run or there was a problem detecting java. Try running `postInstall.js` manually.\n\n## Debugging\n\n        npm install\n        node-gyp build --debug\n        gdb --args `which node` ./node_modules/.bin/nodeunit test\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2012 Near Infinity Corporation\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoeferner%2Fnode-java","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjoeferner%2Fnode-java","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoeferner%2Fnode-java/lists"}