
CodecLib
更简便地使用Hytale配置编解码器
CodecLib
CodecLib 是一个轻量级的 Hytale 配置库,能够通过反射自动创建 BuilderCodec。它允许您使用简单的 POJO(普通旧式 Java 对象) 创建复杂的配置文件和数据结构,而无需手动定义每个字段和编解码器。
🚀 使用方法
1. 基本配置
创建一个包含要序列化字段的类。您可以初始化这些字段以设置默认值。
/**
* 规则:
* 1. 字段不能是 final、static 或 transient。
* 2. 字段必须以大写字母开头(Hytale Config 约定)。
* 3. 确保您使用的自定义类也使用了 @Configuration 注解。
*/
@Configuration
public class MyConfig {
private String ExampleField = "defaultValue";
@FieldName("DifferentName") // 在 config.json 中,此字段将命名为 "DifferentName"
private String exampleFieldButWithDifferentName = "defaultValue2";
@SkipConfigField // 这将跳过该字段的序列化
private String thisFieldWillNotExist = "defaultValue3";
private int ExampleIntField = 42;
}
2. 生成编解码器
使用 CodecFactory 生成编解码器并加载配置。
// ... 在您的插件中 ...
public CodecLibPlugin(@Nonnull JavaPluginInit init) {
super(init);
instance = this;
// 可选:您可以为您自己的类型注册自定义编解码器
CodecFactory.registerCustomCodec(Path.class, Codec.PATH);
// 直接使用 CodecFactory.createClassCodec(YourClass.class) 作为 Codec
CONFIG = withConfig("yourcustomconfig", CodecFactory.createClassCodec(ExampleConfig.class));
}
@Override
protected void setup() {
CONFIG.save(); // 您可以像这样正常保存
assert Objects.equals(CONFIG.get().getExampleField(), "defaultValue");
assert Objects.equals(CONFIG.get().getExampleIntField(), 42);
assert Objects.equals(CONFIG.get().getExampleFieldButWithDifferentName(), "defaultValue2");
}
3. 嵌套对象
您可以将对象放入其他对象中。CodecLib 会递归地为它们生成编解码器。
@Configuration
public class DatabaseConfig {
public String Host = "localhost";
public int Port = 3306;
}
@Configuration
public class MainConfig {
public String PluginName = "MyPlugin";
// 这将自动处理!
public DatabaseConfig Database = new DatabaseConfig();
}
📦 安装
如果已托管,请替换为实际的 JitPack/Maven 指令,否则请遮蔽或复制该库。
Gradle (Groovy)
repositories {
maven { url 'https://jitpack.io' }
}
dependencies {
implementation 'com.github.Emibergo02:CodecLib:main-SNAPSHOT'
}
// 建议在您的项目中重定位包
shadowJar {
relocate 'dev.unnm3d.codeclib', 'your.package.name.codeclib'
}
✅ 支持的类型
该库自动解析以下类型的编解码器:
String、Boolean、Integer、Double、Long、Float、Byte、ShortUUID、InstantString[]、int[]、double[]、long[]、float[]- 任何其他 Class(通过递归)
- 更多类型即将推出,敬请关注
📋 要求
- Java 25+
- Hytale Server API(用于
BuilderCodec、Codec等)
还没有人评论,去客户端里说两句吧。
评论在新手盒子客户端中发表,这里同步展示。