Template Classes
Named classes defined inline within scripts and templates without needing a separate file
Template classes (also called local classes) let you define named classes inline within your .bxs scripts or .bxm templates without needing a separate .bx file. This means you can define helper classes right where you need them and use them on try.boxlang.io which runs scripts in a single compilation unit.
class Person {
function getName() {
return "Brad";
}
}
result = new Person().getName();
// Result: "Brad"📥 Defining Template Classes
A template class is declared using the class keyword with a name, inline in a .bxs script or .bxm template:
class Greeter {
function greet( name ) {
return "Hello, " & name & "!";
}
}Unlike file-based classes (.bx files), template classes are only available within that compilation unit — the script or template where they are defined.
🆕 Instantiating
Template classes are instantiated using new just like file-based classes:
Template class instances are IClassRunnable objects, the same as file-based class instances.
🏗️ Hoisting
Template classes are hoisted to the top of the compilation unit, meaning you can instantiate them before their textual definition:
📦 Multiple Classes
You can define multiple template classes in the same script:
📝 Properties and Constructors
Template classes support properties and init() constructors:
Constructor with Arguments
🧊 Static Members
Template classes support static blocks, static variables, and static methods:
Static Variables
Static Methods
🔗 Inheritance
Extending Another Template Class
Multi-Level Inheritance
Using super()
🔒 Final and Abstract
Final Classes
A final class cannot be extended:
Abstract Classes
An @abstract class cannot be instantiated directly but can be extended:
☕ Java Interoperability
Template classes can implement Java interfaces and extend Java classes.
Implementing a Java Interface
Extending a Java Class
Implementing Comparable
📥 Imports
Template classes can use imports from the enclosing script:
📊 Metadata
Template classes expose full metadata via getMetadata(), getClassMetadata(), and $bx.meta.
getMetadata() on Instance
getClassMetadata() by Name
$bx.meta
🖼️ Templates
Template classes work inside <bx:script> islands in .bxm templates:
Nested Classes in Templates
Template classes can contain nested (inner) classes in templates:
⚠️ Naming Restrictions
Duplicate Names
Duplicate template class names are not allowed (case-insensitive):
Import Conflicts
A template class name cannot conflict with an import:
Cannot Define Inside a Function
Template classes cannot be defined inside a function body:
Last updated
Was this helpful?
