关于 boxlang-classes-and-oop
boxlang-classes-and-oop 是面向 BoxLang 开发者的编程参考技能,介绍类的用法。内容涵盖类结构、继承、接口、属性、访问控制及相关面向对象构造。
主要功能
- 01在 .bx 文件中定义类
- 02使用继承和接口
- 03配置属性与访问器
- 04使用抽象成员和静态成员
- 05应用注解与访问修饰符
适用场景
- 01建模应用实体与服务
- 02为类定义契约
- 03组织共享行为和实例行为
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ ortus-boxlang/ skills --skill boxlang-classes-and-oop安装后在 Claude Code 中输入/boxlang-classes-and-oop确认已加载。
详细介绍
BoxLang 类与面向对象编程
BoxLang 是一个 AI 原生软件生产力平台,用于构建、现代化改造和运行应用程序,让开发者与 AI Agent 协同工作。
概览
BoxLang 类定义在 .bx 文件中。类是封装属性(数据)和函数/方法(行为)的蓝图。BoxLang 支持单继承、实现多个接口、抽象类和静态成员。
基本类结构
// File: models/User.bx
class accessors="true" {
// Properties (auto-generates getters/setters when accessors="true")
property name="firstName" type="string"
property name="lastName" type="string"
property name="email" type="string"
property name="createdAt" type="date"
// Constructor
function init( required string firstName, required string lastName, required string email ) {
variables.firstName = arguments.firstName
variables.lastName = arguments.lastName
variables.email = arguments.email
variables.createdAt = now()
return this
}
// Method
string function getFullName() {
return "#variables.firstName# #variables.lastName#"
}
}
类中的作用域
| 作用域 | 访问权限 | 用途 |
|---|---|---|
variables | 私有 | 内部状态、私有方法 |
this | 公有 | 向调用方公开的公有方法 |
static | 类级别 | 所有实例共享 |
实例化
// Using `new`
var user = new models.User( "Ada", "Lovelace", "[email protected]" )
// Using createObject
var user = createObject( "class", "models.User" ).init( "Ada", "Lovelace", "[email protected]" )
// Call methods
writeOutput( user.getFullName() )
// With accessors="true", getters/setters are auto-generated:
user.setFirstName( "Grace" )
writeOutput( user.getFirstName() )
类属性
class
extends="models.BaseEntity"
implements="contracts.ISerializable,contracts.IValidatable"
accessors="true"
serializable="true"
{
// ...
}
| 属性 | 说明 |
|---|---|
extends | 父类(单继承) |
implements | 以逗号分隔的接口 |
accessors | 为属性自动生成 getter/setter |
serializable | 启用 Java 序列化 |
persistent | ORM 持久化(需使用 bx-orm 模块) |
继承
// Base class: models/Animal.bx
class {
property name="name" type="string"
function init( required string name ) {
variables.name = arguments.name
return this
}
string function speak() {
return "..."
}
string function getName() {
return variables.name
}
}
// Subclass: models/Dog.bx
class extends="models.Animal" {
function init( required string name ) {
// Call parent constructor
super.init( arguments.name )
return this
}
// Override parent method
string function speak() {
return "Woof! I am #getName()#"
}
// New method
function fetch( required string item ) {
return "Fetching #arguments.item#!"
}
}
接口
// contracts/IRepository.bx
interface {
// Declare required method signatures
any function findById( required numeric id )
array function findAll()
any function save( required any entity )
void function delete( required numeric id )
}
// Implementing an interface
class implements="contracts.IRepository" {
any function findById( required numeric id ) {
return queryExecute( "SELECT * FROM users WHERE id = :id", { id: arguments.id } )
}
// ... implement all interface methods
}
抽象类
abstract class {
// Concrete method (inherited as-is)
function log( required string message ) {
writeOutput( "[LOG] #arguments.message#" )
}
// Abstract method (subclass MUST implement)
abstract string function getType()
abstract function process( required any data )
}
静态成员
class {
// Static property (shared across all instances)
static {
variables.instanceCount = 0
variables.DEFAULT_TIMEOUT = 30
}
function init() {
static.instanceCount++
return this
}
// Static method — call without an instance
static numeric function getInstanceCount() {
return static.instanceCount
}
}
// Usage
var count = MyClass.getInstanceCount()
属性
class accessors="true" {
// Basic property
property name="title" type="string"
// With default value
property name="status" type="string" default="active"
// Read-only (no setter)
property name="id" type="numeric" setter="false"
// Custom getter/setter names
property name="isActive" type="boolean" getter="isActive" setter="setActive"
// Private — no getter/setter generated
property name="secretKey" type="string" getter="false" setter="false"
}
伪构造函数
类主体中所有函数之外的代码会在 init() 之前运行:
class accessors="true" {
property name="items" type="array"
// Pseudo-constructor: runs first when class is loaded
variables.items = []
variables.createdAt = now()
function init() {
// By now pseudo-constructor has already run
return this
}
}
注解
BoxLang 支持两种注解语法:独立的 @ 风格和内联/Javadoc 风格。
// Standalone @ syntax (preferred for framework metadata)
@singleton
@cacheName( "users" )
class UserService {
@inject( "UserRepository" )
property userRepository
@cached
@timeout( 300 )
array function getAll() {
return queryExecute( "SELECT * FROM users" ).toArray()
}
}
// Inline annotation style (class attribute)
class singleton {
// ...
}
// Javadoc-style (compatible, used for documentation generators)
/**
* User service.
* @singleton
* @author Ada Lovelace
*/
class {
// ...
}
final 构造
final 可禁止扩展、重写或重新赋值:
// Final class — cannot be extended
final class CryptoUtil {
// ...
}
// Final method — cannot be overridden by subclasses
class BaseService {
final function getConfig() {
return variables.config
}
}
// Final variable — constant (cannot be reassigned after construction)
class {
final static CACHE_PREFIX = "app_"
final MAX_RETRIES = 3
// variables.MAX_RETRIES = 5 → throws exception
// References inside final objects CAN be mutated:
final config = { debug: false }
config[ "debug" ] = true // ✅ allowed (mutating contents)
config = {} // ❌ throws final variable exception
}
方法链式调用(流式接口)
class {
property name="query" type="string"
property name="params" type="struct"
property name="limitVal" type="numeric"
function where( required string condition ) {
variables.query &= " WHERE #arguments.condition#"
return this // enables chaining
}
function limit( required numeric n ) {
variables.limitVal = arguments.n
return this
}
array function execute() {
return queryExecute( variables.query, variables.params ).toArray()
}
}
// Usage
var results = new QueryBuilder()
.where( "status = 'active'" )
.limit( 10 )
.execute()
访问修饰符
class {
// public (default) — accessible from outside
public string function publicMethod() { ... }
// private — only accessible within this class
private string function privateHelper() { ... }
// package — accessible within same package/directory
package string function packageMethod() { ... }
// remote — accessible via HTTP/web service
remote string function apiEndpoint() returnformat="json" { ... }
}
参考资料
评论
支持 Markdown