Skip to main content

Java Interop

BBj runs on the JVM and gives you direct access to any Java class. You can create Java objects, call their methods, implement Java interfaces in BBj classes, and use the full standard library plus any JAR on the classpath. BBj 25 requires Java 21, so all modern Java APIs are available.

At a Glance

FeatureSyntaxPurpose
Import classuse java.util.HashMapReference class by short name
Create objectobj! = new HashMap()Instantiate Java class
Call methodobj!.put("key", "value")Invoke Java method
Implement interfaceclass public X implements ComparatorBBj class implements Java interface
Handle exceptionvalue! = obj!.method(ERR=handler)Catch Java exceptions as BBj errors
Get exceptionBBjAPI().getLastJavaException()Inspect the Java exception object

This chapter covers three tiers: basics (importing and using Java classes), advanced patterns (interfaces, generics, classpath configuration), and practical libraries (JSON, HTTP, hashing, and more).

For Java, Python, and C# Developers

TaskJavaPythonC#BBj
Import classimport java.util.HashMap;from collections import OrderedDictusing System.Collections;use java.util.HashMap
Create instancenew HashMap()OrderedDict()new Dictionary()new HashMap()
Call methodobj.put("k", "v")obj.update({"k": "v"})obj.Add("k", "v")obj!.put("k", "v")
Implement interfaceclass X implements Yclass X(Y):class X : Yclass public X implements Y
Cast object(String) objN/A (duck typing)(string) objcast(String, obj!)
Get Java exceptionN/A (native)N/AN/ABBjAPI().getLastJavaException()

Since BBj runs on the JVM, you use Java classes directly -- no bridge or FFI layer needed. use statements work like Java imports, and new creates Java objects the same way. For the complete cross-language reference, see BBj for Java, Python, and C# Developers.

Complete Runnable Examples

This chapter's code snippets illustrate individual concepts. For complete, runnable programs you can open directly in the BBj IDE, see the sample files in samples/09-java-interop/:

  • java_basics.bbj -- Creating Java objects, calling methods, iterating collections
  • java_interfaces.bbj -- Implementing java.util.Comparator in a BBj class
  • http_request.bbj -- HTTP GET request with java.net.HttpURLConnection
  • json_example.bbj -- JSON parsing with org.json (bundled with BBj 25.x)
  • utility_examples.bbj -- Base64, SHA-256 hashing, and UUID generation

See Running Samples for setup instructions.