Compare commits

...
6 Commits
Author SHA1 Message Date
minglipro 28a2987dc3 fix(json): 修正 BaseJsonWriter 中 BaseJsonJudgment 的导入路径
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-17 21:18:25 +08:00
minglipro 8069de37f2 feat(tuple): 实现 Tuple.compareTo 字典序比较并发布 5.5.2
替换原 TODO 占位实现:同类型可比较元素按自然顺序逐位比较,其余按
字符串形式回退,公共前缀相等时短元组在前;新增 TestTuple 6 个用例
全部通过;CHANGELOG 增加 5.5.2 条目,VERSIONS 5.5.1 -> 5.5.2。
2026-11-17 21:17:01 +08:00
minglipro 51eb838a36 docs: 补全 src 全部 Kotlin KDoc 与 Java Javadoc,版本升级至 5.5.1
Gitea Actions Build / Build (push) Canceled after 0s
为所有缺失文档的公开声明补充中文 KDoc/Javadoc(含 exception、json、
springboot、tuple 生成类、MediaType 枚举项及测试),仅插入注释不改代码;
gradle.properties VERSIONS 5.4.4 -> 5.5.1。
2026-11-17 21:07:58 +08:00
minglipro d0887ea1f7 refactor(json): 重构 JSON 转换器体系,新增 reader/writer/judgment 抽象
移除按类型划分的 BaseJson*Converter,统一由 BaseJsonConverter 与
JsonConverterUtils 处理;为 Jackson2/Jackson3 分别实现 JsonReader、
JsonWriter 与 ReaderJudgment,并同步更新 SpringBoot 自动配置与测试。
2026-11-17 20:35:19 +08:00
minglipro 16da482de7 v5.4.4
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-17 10:25:13 +08:00
minglipro aa83f575b1 v5.4.4
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-17 10:16:43 +08:00
164 changed files with 18900 additions and 1249 deletions
+51
View File
@@ -0,0 +1,51 @@
# Changelog
本文件记录 mingli-utils 各版本的主要变更。
## [5.5.2] - 2026-11-17
### 新增
- **tuple**:实现 `Tuple.compareTo` 字典序比较——同类型可比较元素按自然顺序,
其余按字符串形式比较;公共前缀相等时元素个数较少的元组在前。
新增 `TestTuple` 测试覆盖 6 种比较场景。
## [5.5.1] - 2026-11-17
### 新增
- **json**:新增 `reader` / `witer` / `judgment` 三组抽象,为 Jackson2 与 Jackson3 分别提供
`JsonReader`、`JsonArrayReader`、`JsonObjectReader`、`JsonWriter`、`ArrayWriter`、`ObjectWriter`
与 `ReaderJudgment` 实现(`BaseJsonReader` / `BaseJsonWriter` / `BaseJsonJudgment` 等基类)。
- **exception**:新增 `JsonFormatException`,表示 JSON 格式错误,继承自 `JsonException`。
- **time**:`DateTime.now(zone)` 支持指定时区;新增 `DateTime.atZone(zoneId)` 时区转换方法,
`toString()` 输出包含 `zoneId`。
### 变更
- **json**:重构转换器体系——移除按类型划分的 `BaseJsonIntConverter`、`BaseJsonStringConverter`
等 10 个转换器及 `JsonConverter` 接口,统一由 `BaseJsonConverter` 与 `JsonConverterUtils` 处理;
简化 `DateTimeJsonConverter`、`UUIDJsonConverter`、`NetworkEndpointJsonConverter` 与
Jackson2/Jackson3 序列化/反序列化桥接实现;精简 `JSONA` 与 `JsonApi` 门面。
- **tuple**:`Tuple` 声明实现 `Comparable<Tuple>`;迭代器改为基于 `toMutableList()` 的简化实现。
- **springboot**:`JsonAutoConfiguration` 与 `JacksonJsonBuilder` / `JacksonJsonBuilderImpl`
同步适配新的 JSON 转换器体系。
### 文档
- 补全 src 下全部 Kotlin 文件的中文 KDoc 与 Java 文件的 Javadoc(约 1.3 万处),
覆盖 exception、json、springboot、mybatis/mybatisplus、thread/netty/http、
Tuple1~Tuple100 生成类、MediaType 全部枚举项及测试代码;已有文档保持不变。
## [5.4.4] - 2026-11-17
- 构建脚本调整(build.gradle.kts 发布配置完善)。
- SpringBoot 自动配置重构:新增 `JsonAutoConfiguration` 与 `JacksonBuilder`,
精简 Jackson2/Jackson3 JsonApi 自动配置。
## [5.4.3] - 2026-11-17
- 新增 `JacksonJsonBuilder` / `JacksonJsonBuilderImpl` 构建器。
- `DateTime`、`UUID` 小幅调整;补充 log4j2 测试配置。
## [5.4.2] - 2026-11
- 修复 `JSONA.jsonApi` 编译错误。
- **mybatisplus**:新增 `FastBaseIServiceNew3518`(适配 MyBatis-Plus 3.5.18)。
## [5.4.0] - 2026-11
- **mybatisplus**:新增 `FastBaseIService`。
- 全项目统一 Tab 缩进并补全尾随逗号。
+40 -15
View File
@@ -16,12 +16,37 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils * ModuleName mingli-utils
* CurrentFile build.gradle.kts * CurrentFile build.gradle.kts
* LastUpdate 2026-10-28 21:50:32 * LastUpdate 2026-11-17 10:19:02
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
import java.time.LocalDateTime import java.time.LocalDateTime
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
import kotlin.math.sign
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils
* CurrentFile build.gradle.kts
* LastUpdate 2026-11-17 10:18:28
* UpdateUser MingLiPro
*/
plugins { plugins {
idea idea
@@ -61,7 +86,8 @@ kotlin {
repositories { repositories {
mavenLocal() mavenLocal()
maven { maven {
url = uri("https://maven.mingliqiye.com/") name = "mingliqiye-public"
url = uri("https://repository.mingliqiye.com/repository/maven-public/")
} }
mavenCentral() mavenCentral()
} }
@@ -160,32 +186,31 @@ tasks.withType<org.gradle.jvm.tasks.Jar> {
} }
val isJdk8Build = project.findProperty("buildForJdk8") == "true" val isJdk8Build = project.findProperty("buildForJdk8") == "true"
dokka {
pluginsConfiguration.html {
customAssets.from("logo.png")
}
}
tasks.register<Jar>("javaDocJar") { tasks.register<Jar>("javaDocJar") {
group = "build" group = "build"
archiveClassifier.set("javadoc-dec") archiveClassifier.set("javadoc")
dependsOn("dokkaGeneratePublicationJavadoc") dependsOn("dokkaGenerateJavadoc")
from(buildDir.resolve("dokka/javadoc")) from(buildDir.resolve("dokka/javadoc"))
} }
tasks.register<Jar>("kotlinDocJar") { tasks.register<Jar>("kotlinDocJar") {
group = "build" group = "build"
archiveClassifier.set("javadoc") archiveClassifier.set("kotlindoc")
dependsOn("dokkaGeneratePublicationHtml") dependsOn("dokkaGeneratePublicationHtml")
from(buildDir.resolve("dokka/html")) from(buildDir.resolve("dokka/html"))
} }
publishing { publishing {
repositories {
maven {
name = "mingliqiye"
url = uri("https://repository.mingliqiye.com/repository/maven")
credentials {
username = System.getenv("mingliqiye.username")
password = System.getenv("mingliqiye.password")
}
}
}
publications { publications {
create<MavenPublication>("mavenJava") { create<MavenPublication>("mavenJava") {
from(components["java"]) from(components["java"])
artifact(tasks.named("javaDocJar"))
artifact(tasks.named("kotlinDocJar")) artifact(tasks.named("kotlinDocJar"))
artifactId = ARTIFACTID artifactId = ARTIFACTID
pom { pom {
+2 -2
View File
@@ -16,10 +16,10 @@
# ProjectName mingli-utils # ProjectName mingli-utils
# ModuleName mingli-utils # ModuleName mingli-utils
# CurrentFile gradle.properties # CurrentFile gradle.properties
# LastUpdate 2026-11-09 19:49:52 # LastUpdate 2026-11-17 09:07:20
# UpdateUser MingLiPro # UpdateUser MingLiPro
# #
JDKVERSIONS=17 JDKVERSIONS=17
GROUPSID=com.mingliqiye.utils GROUPSID=com.mingliqiye.utils
ARTIFACTID=mingli-utils ARTIFACTID=mingli-utils
VERSIONS=5.4.3 VERSIONS=5.5.2
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

@@ -26,7 +26,16 @@ import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.cfg.MapperBuilder; import tools.jackson.databind.cfg.MapperBuilder;
/**
* Jackson 3 API 的 Java 辅助类,用于在 Java 侧调用 Kotlin 内联/受限 API。
*/
public class Jackson3ApiJavaHelper { public class Jackson3ApiJavaHelper {
/**
* 基于现有 ObjectMapper 创建可重新配置的 MapperBuilder。
*
* @param objectMapper 需要重建的 ObjectMapper 实例
* @return 由该 ObjectMapper 派生的 MapperBuilder
*/
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
static MapperBuilder rebuild(ObjectMapper objectMapper) { static MapperBuilder rebuild(ObjectMapper objectMapper) {
return objectMapper.rebuild(); return objectMapper.rebuild();
@@ -29,7 +29,13 @@ import java.net.InetAddress;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
/**
* 工具库入口类,提供启动 Banner 打印以及进程、主机、用户等基础信息的获取方法。
*/
public class Main { public class Main {
/**
* 启动时打印的 ASCII 艺术 Banner 文本
*/
public final static String BANNER = public final static String BANNER =
"| $$\\ $$\\ $$\\ $$\\ $$\\ $$$$$$$$\\ $$$$$$\\ \n" + "| $$\\ $$\\ $$\\ $$\\ $$\\ $$$$$$$$\\ $$$$$$\\ \n" +
"| $$$\\ $$$ |$$ | $$ | $$ |\\__$$ __|$$ __$$\\ \n" + "| $$$\\ $$$ |$$ | $$ | $$ |\\__$$ __|$$ __$$\\ \n" +
@@ -40,6 +46,11 @@ public class Main {
"| $$ | \\_/ $$ |$$$$$$$$\\\\$$$$$$ | $$ | \\$$$$$$ \n" + "| $$ | \\_/ $$ |$$$$$$$$\\\\$$$$$$ | $$ | \\$$$$$$ \n" +
"| \\__| \\__|\\________|\\______/ \\__| \\______/ \n|\n"; "| \\__| \\__|\\________|\\______/ \\__| \\______/ \n|\n";
/**
* 程序入口,打印 Banner 与构建元数据信息,打印失败时静默忽略。
*
* @param args 命令行参数(未使用)
*/
public static void main(String[] args) { public static void main(String[] args) {
try { try {
printb(); printb();
@@ -47,6 +58,11 @@ public class Main {
} }
} }
/**
* 获取当前进程 PID 字符串。
*
* @return 当前进程 PID;获取失败时返回 "-1"
*/
public static String getPid() { public static String getPid() {
try { try {
var name = ManagementFactory.getRuntimeMXBean().getName(); var name = ManagementFactory.getRuntimeMXBean().getName();
@@ -61,6 +77,11 @@ public class Main {
} }
} }
/**
* 获取计算机名,依次尝试环境变量 COMPUTERNAME、HOSTNAME 与本机主机名。
*
* @return 计算机名;获取失败时返回 "unknown"
*/
public static String getComputerName() { public static String getComputerName() {
try { try {
var name = System.getenv("COMPUTERNAME"); var name = System.getenv("COMPUTERNAME");
@@ -76,6 +97,11 @@ public class Main {
} }
} }
/**
* 获取当前用户名,依次尝试环境变量 USERNAME、USER 与 user.name。
*
* @return 当前用户名;获取失败时返回 "unknown"
*/
public static String getUserName() { public static String getUserName() {
try { try {
String user = System.getenv("USERNAME"); String user = System.getenv("USERNAME");
@@ -96,6 +122,12 @@ public class Main {
} }
/**
* 打印 Banner 及构建元数据、JDK 版本、PID、计算机名、用户名与当前时间。
* 若元数据资源不存在则直接返回。
*
* @throws IOException 读取元数据资源失败时抛出
*/
public static void printb() throws IOException { public static void printb() throws IOException {
InputStream inputStream = Main.class.getResourceAsStream("/META-INF/meta-data"); InputStream inputStream = Main.class.getResourceAsStream("/META-INF/meta-data");
if (inputStream == null) return; if (inputStream == null) return;
@@ -34,10 +34,15 @@ import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec import javax.crypto.spec.SecretKeySpec
/** 加密算法名称:AES。 */
const val ALGORITHM = "AES" const val ALGORITHM = "AES"
/** AES 加密变换模式:GCM 模式,无填充。 */
const val TRANSFORMATION = "AES/GCM/NoPadding" const val TRANSFORMATION = "AES/GCM/NoPadding"
/** GCM 模式初始化向量(IV)长度,单位字节。 */
const val GCM_IV_LENGTH = 12 const val GCM_IV_LENGTH = 12
/** GCM 模式认证标签(Tag)长度,单位字节。 */
const val GCM_TAG_LENGTH = 16 const val GCM_TAG_LENGTH = 16
/** 全局安全随机数生成器,用于生成加密安全的随机 IV。 */
val SECURE_RANDOM = SecureRandom() val SECURE_RANDOM = SecureRandom()
@@ -33,12 +33,26 @@ import javax.lang.model.type.TypeMirror
import javax.tools.StandardLocation import javax.tools.StandardLocation
/**
* [AutoService] 注解的编译期处理器。
*
* 扫描标注了 [AutoService] 的类,收集服务接口与实现类的映射关系,
* 并在编译输出目录的 META-INF/services 下生成对应的服务注册文件。
*/
@SupportedAnnotationTypes("com.mingliqiye.utils.annotation.AutoService") @SupportedAnnotationTypes("com.mingliqiye.utils.annotation.AutoService")
class AutoServiceProcessor : AbstractProcessor() { class AutoServiceProcessor : AbstractProcessor() {
override fun init(processingEnv: ProcessingEnvironment) { override fun init(processingEnv: ProcessingEnvironment) {
super.init(processingEnv) super.init(processingEnv)
} }
/**
* 处理标注了 [AutoService] 的元素,收集服务接口与实现类的映射并生成服务注册文件。
* 若注解未显式指定服务接口,则默认使用该类直接实现的接口。
*
* @param annotations 本轮处理的注解类型集合
* @param roundEnv 当前轮次的处理环境
* @return 是否已处理该注解,存在标注元素时返回 true,否则返回 false
*/
override fun process( override fun process(
annotations: Set<TypeElement>, annotations: Set<TypeElement>,
roundEnv: RoundEnvironment, roundEnv: RoundEnvironment,
@@ -73,6 +87,12 @@ class AutoServiceProcessor : AbstractProcessor() {
return true return true
} }
/**
* 根据服务接口与实现类的映射,在 META-INF/services 目录下生成服务注册文件。
* 实现列表为空或文件创建失败时打印提示信息并跳过。
*
* @param map 服务接口全限定名到实现类全限定名列表的映射
*/
fun processClassAnnotation(map: Map<String, MutableList<String>>) { fun processClassAnnotation(map: Map<String, MutableList<String>>) {
map.forEach { (interfaceName, implementations) -> map.forEach { (interfaceName, implementations) ->
if (implementations.isEmpty()) { if (implementations.isEmpty()) {
@@ -24,6 +24,11 @@ package com.mingliqiye.utils.base
import java.math.BigInteger import java.math.BigInteger
/**
* Base10 编解码器实现类。
*
* 提供字节数组与十进制字符串之间的相互转换功能,基于 [BigInteger] 实现。
*/
internal class Base10Codec : BaseCodec { internal class Base10Codec : BaseCodec {
/** /**
@@ -32,7 +32,13 @@ package com.mingliqiye.utils.base
*/ */
internal class Base256Codec : BaseCodec { internal class Base256Codec : BaseCodec {
/**
* 伴生对象,持有 Base256 的编码字符集及其反向索引表。
*/
companion object { companion object {
/**
* Base256 编码字符集,共 256 个字符,数组索引即对应的字节值(0~255)。
*/
val code = arrayOf( val code = arrayOf(
'!', '!',
'#', '#',
@@ -291,6 +297,9 @@ internal class Base256Codec : BaseCodec {
'▘', '▘',
'▙' '▙'
) )
/**
* 字符到字节值的反向映射表,用于解码时快速查找字符对应的索引。
*/
val codeMap = code.mapIndexed { index, c -> c to index }.toMap() val codeMap = code.mapIndexed { index, c -> c to index }.toMap()
} }
@@ -303,6 +312,13 @@ internal class Base256Codec : BaseCodec {
return String(result) return String(result)
} }
/**
* 将 Base256 字符串解码为字节数组。
*
* @param string 待解码的字符串,所有字符必须属于编码字符集
* @return 解码后的字节数组
* @throws NullPointerException 如果字符串中包含字符集之外的字符
*/
override fun decode(string: String): ByteArray { override fun decode(string: String): ByteArray {
val result = ByteArray(string.length) val result = ByteArray(string.length)
for (i in string.indices) { for (i in string.indices) {
@@ -22,6 +22,11 @@
package com.mingliqiye.utils.base package com.mingliqiye.utils.base
/**
* Base2 编解码器实现类。
*
* 提供字节数组与二进制字符串(每字节 8 位,高位在前)之间的相互转换功能。
*/
internal class Base2Codec : BaseCodec { internal class Base2Codec : BaseCodec {
override fun encode(bytes: ByteArray): String { override fun encode(bytes: ByteArray): String {
if (bytes.isEmpty()) return "" if (bytes.isEmpty()) return ""
@@ -34,6 +39,13 @@ internal class Base2Codec : BaseCodec {
return result.toString() return result.toString()
} }
/**
* 将二进制字符串解码为字节数组。
*
* @param string 待解码的二进制字符串,长度必须为 8 的倍数且仅包含字符 '0' 和 '1'
* @return 解码后的字节数组
* @throws IllegalArgumentException 如果字符串长度不是 8 的倍数或包含非法字符
*/
override fun decode(string: String): ByteArray { override fun decode(string: String): ByteArray {
if (string.length % 8 != 0) { if (string.length % 8 != 0) {
throw IllegalArgumentException( throw IllegalArgumentException(
@@ -24,25 +24,25 @@ package com.mingliqiye.utils.base
import java.util.* import java.util.*
/* /**
* Base64编解码工具类 * Base64编解码工具类
* 提供Base64编码和解码功能的实现 * 提供Base64编码和解码功能的实现
*/ */
internal class Base64Codec : BaseCodec { internal class Base64Codec : BaseCodec {
/* /**
* Base64编码器实例 * Base64编码器实例
* 用于执行字节数组到Base64字符串的编码操作 * 用于执行字节数组到Base64字符串的编码操作
*/ */
val encoder: Base64.Encoder = Base64.getEncoder() val encoder: Base64.Encoder = Base64.getEncoder()
/* /**
* Base64解码器实例 * Base64解码器实例
* 用于执行Base64字符串到字节数组的解码操作 * 用于执行Base64字符串到字节数组的解码操作
*/ */
val decoder: Base64.Decoder = Base64.getDecoder() val decoder: Base64.Decoder = Base64.getDecoder()
/* /**
* 将字节数组编码为Base64字符串 * 将字节数组编码为Base64字符串
* *
* @param bytes 待编码的字节数组 * @param bytes 待编码的字节数组
@@ -52,7 +52,7 @@ internal class Base64Codec : BaseCodec {
return encoder.encodeToString(bytes) return encoder.encodeToString(bytes)
} }
/* /**
* 将Base64字符串解码为字节数组 * 将Base64字符串解码为字节数组
* *
* @param string 待解码的Base64字符串 * @param string 待解码的Base64字符串
@@ -0,0 +1,65 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Base64NoPaddingCodec.kt
* LastUpdate 2026-11-16 14:24:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.base
import java.util.*
/**
* 无填充 Base64 URL 编解码器实现类。
*
* 使用 URL 安全的 Base64 字母表,编码结果不带末尾的 '=' 填充字符。
*/
internal class Base64NoPaddingCodec : BaseCodec {
/**
* Base64编码器实例
* 用于执行字节数组到Base64字符串的编码操作
*/
val encoder: Base64.Encoder = Base64.getUrlEncoder().withoutPadding()
/**
* Base64解码器实例
* 用于执行Base64字符串到字节数组的解码操作
*/
val decoder: Base64.Decoder = Base64.getUrlDecoder()
/**
* 将字节数组编码为Base64字符串
*
* @param bytes 待编码的字节数组
* @return 编码后的Base64字符串
*/
override fun encode(bytes: ByteArray): String {
return encoder.encodeToString(bytes)
}
/**
* 将Base64字符串解码为字节数组
*
* @param string 待解码的Base64字符串
* @return 解码后的字节数组
*/
override fun decode(string: String): ByteArray {
return decoder.decode(string)
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile Base64UrlCodec.kt * CurrentFile Base64UrlCodec.kt
* LastUpdate 2026-03-12 10:34:36 * LastUpdate 2026-11-16 14:24:59
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -24,21 +24,26 @@ package com.mingliqiye.utils.base
import java.util.* import java.util.*
/**
* URL 安全 Base64 编解码器实现类。
*
* 使用 '-' 和 '_' 替代标准 Base64 中的 '+' 和 '/',适用于 URL 与文件名场景。
*/
internal class Base64UrlCodec : BaseCodec { internal class Base64UrlCodec : BaseCodec {
/* /**
* Base64编码器实例 * Base64编码器实例
* 用于执行字节数组到Base64字符串的编码操作 * 用于执行字节数组到Base64字符串的编码操作
*/ */
val encoder: Base64.Encoder = Base64.getUrlEncoder() val encoder: Base64.Encoder = Base64.getUrlEncoder()
/* /**
* Base64解码器实例 * Base64解码器实例
* 用于执行Base64字符串到字节数组的解码操作 * 用于执行Base64字符串到字节数组的解码操作
*/ */
val decoder: Base64.Decoder = Base64.getUrlDecoder() val decoder: Base64.Decoder = Base64.getUrlDecoder()
/* /**
* 将字节数组编码为Base64字符串 * 将字节数组编码为Base64字符串
* *
* @param bytes 待编码的字节数组 * @param bytes 待编码的字节数组
@@ -48,7 +53,7 @@ internal class Base64UrlCodec : BaseCodec {
return encoder.encodeToString(bytes) return encoder.encodeToString(bytes)
} }
/* /**
* 将Base64字符串解码为字节数组 * 将Base64字符串解码为字节数组
* *
* @param string 待解码的Base64字符串 * @param string 待解码的Base64字符串
@@ -29,6 +29,9 @@ package com.mingliqiye.utils.base
*/ */
internal class Base91Codec : BaseCodec { internal class Base91Codec : BaseCodec {
/**
* 伴生对象,持有 Base91 的编码表与解码表。
*/
companion object { companion object {
/** /**
* Base91 编码表,共 91 个可打印 ASCII 字符。 * Base91 编码表,共 91 个可打印 ASCII 字符。
@@ -16,23 +16,55 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile BaseType.kt * CurrentFile BaseType.kt
* LastUpdate 2026-03-12 10:08:42 * LastUpdate 2026-11-16 14:21:51
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.base package com.mingliqiye.utils.base
enum class BaseType(val baseCodec: BaseCodec) : BaseCodec { import com.mingliqiye.utils.base.code.BASE10 as CODE_BASE10
import com.mingliqiye.utils.base.code.BASE16 as CODE_BASE16
import com.mingliqiye.utils.base.code.BASE2 as CODE_BASE2
import com.mingliqiye.utils.base.code.BASE256 as CODE_BASE256
import com.mingliqiye.utils.base.code.BASE64 as CODE_BASE64
import com.mingliqiye.utils.base.code.BASE64_NO_PADDING as CODE_BASE64_NO_PADDING
import com.mingliqiye.utils.base.code.BASE64_URL as CODE_BASE64_URL
import com.mingliqiye.utils.base.code.BASE91 as CODE_BASE91
BASE2(com.mingliqiye.utils.base.code.BASE2), /**
BASE10(com.mingliqiye.utils.base.code.BASE10), * Base 编码类型枚举。
BASE16(com.mingliqiye.utils.base.code.BASE16), *
BASE64(com.mingliqiye.utils.base.code.BASE64), * 每个枚举项持有一个编解码器的工厂函数,枚举本身实现了 [BaseCodec],
BASE64URL(com.mingliqiye.utils.base.code.BASE64URL), * 可直接作为编解码器使用,编码与解码操作委托给对应的编解码器实例。
BASE91(com.mingliqiye.utils.base.code.BASE91), *
BASE256(com.mingliqiye.utils.base.code.BASE256); * @param baseCodec 编解码器的工厂函数,每次访问 [codec] 时调用以创建实例
*/
enum class BaseType(private val baseCodec: () -> BaseCodec) : BaseCodec {
override fun encode(bytes: ByteArray) = baseCodec.encode(bytes) /** 二进制(Base2)编解码。 */
override fun decode(string: String) = baseCodec.decode(string) BASE2(::CODE_BASE2),
/** 十进制(Base10)编解码。 */
BASE10(::CODE_BASE10),
/** 十六进制(Base16)编解码。 */
BASE16(::CODE_BASE16),
/** 标准 Base64 编解码。 */
BASE64(::CODE_BASE64),
/** URL 安全的 Base64 编解码。 */
BASE64_URL(::CODE_BASE64_URL),
/** 无填充(不带末尾 '=')的 URL 安全 Base64 编解码。 */
BASE64_NO_PADDING(::CODE_BASE64_NO_PADDING),
/** Base91 编解码。 */
BASE91(::CODE_BASE91),
/** Base256 编解码。 */
BASE256(::CODE_BASE256);
/**
* 获取当前类型对应的编解码器实例(每次访问都会通过工厂函数新建)。
*/
val codec
get() = baseCodec()
override fun encode(bytes: ByteArray) = codec.encode(bytes)
override fun decode(string: String) = codec.decode(string)
} }
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile BaseCodes.kt * CurrentFile BaseCodes.kt
* LastUpdate 2026-03-12 10:03:32 * LastUpdate 2026-11-16 14:10:57
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -62,11 +62,25 @@ val BASE64: BaseCodec by lazy {
Base64Codec() Base64Codec()
} }
/**
* 提供Base64 URL编码器的懒加载实例。
* 该编码器用于将数据编码为URL安全的Base64格式。
*/
@get:JvmName("base64Url") @get:JvmName("base64Url")
val BASE64URL: BaseCodec by lazy { val BASE64_URL: BaseCodec by lazy {
Base64UrlCodec() Base64UrlCodec()
} }
/**
* 提供无填充Base64 URL编码器的懒加载实例。
* 该编码器用于将数据编码为URL安全的Base64格式,且结果不带末尾的'='填充字符。
*/
@get:JvmName("base64NoPadding")
val BASE64_NO_PADDING: BaseCodec by lazy {
Base64NoPaddingCodec()
}
/** /**
* 提供Base91编码器的懒加载实例。 * 提供Base91编码器的懒加载实例。
* 该编码器用于将数据编码为Base91格式,具有较高的压缩效率。 * 该编码器用于将数据编码为Base91格式,具有较高的压缩效率。
@@ -29,31 +29,69 @@ import java.security.SecureRandom
import org.mindrot.jbcrypt.BCrypt as JBCrypt import org.mindrot.jbcrypt.BCrypt as JBCrypt
/**
* 使用随机生成的盐对字符串进行 BCrypt 哈希。
*
* @param string 需要哈希的明文字符串
* @return BCrypt 哈希字符串
*/
fun hashpw(string: String): String { fun hashpw(string: String): String {
return hashpw(string, gensalt()) return hashpw(string, gensalt())
} }
/**
* 使用指定的盐对字符串进行 BCrypt 哈希。
*
* @param string 需要哈希的明文字符串
* @param salt BCrypt 盐字符串,默认随机生成
* @return BCrypt 哈希字符串
*/
fun hashpw(string: String, salt: String = gensalt()): String { fun hashpw(string: String, salt: String = gensalt()): String {
return JBCrypt.hashpw(string, salt) return JBCrypt.hashpw(string, salt)
} }
/**
* 验证明文字符串与 BCrypt 哈希是否匹配。
*
* @param string 明文字符串
* @param bcrypted 已生成的 BCrypt 哈希字符串
* @return 匹配返回 true,否则返回 false
*/
fun checkpw(string: String, bcrypted: String): Boolean { fun checkpw(string: String, bcrypted: String): Boolean {
return JBCrypt.checkpw(string, bcrypted) return JBCrypt.checkpw(string, bcrypted)
} }
/**
* 生成默认工作因子(10)的 BCrypt 盐。
*
* @return BCrypt 盐字符串
*/
fun gensalt(): String { fun gensalt(): String {
return JBCrypt.gensalt() return JBCrypt.gensalt()
} }
/**
* 生成指定工作因子的 BCrypt 盐。
*
* @param long 工作因子(log2 迭代次数),值越大计算越慢
* @return BCrypt 盐字符串
*/
fun gensalt(long: Int): String { fun gensalt(long: Int): String {
return JBCrypt.gensalt(long) return JBCrypt.gensalt(long)
} }
/**
* 使用指定的安全随机数生成器生成 BCrypt 盐。
*
* @param long 工作因子(log2 迭代次数)
* @param secureRandom 用于生成盐的安全随机数生成器
* @return BCrypt 盐字符串
*/
fun gensalt(long: Int, secureRandom: SecureRandom): String { fun gensalt(long: Int, secureRandom: SecureRandom): String {
return JBCrypt.gensalt(long, secureRandom) return JBCrypt.gensalt(long, secureRandom)
} }
@@ -198,6 +198,9 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
return "ByteBufferWrapper(capacity=$capacity, position=$position, limit=$limit, remaining=$remaining)#${hashCode()}" return "ByteBufferWrapper(capacity=$capacity, position=$position, limit=$limit, remaining=$remaining)#${hashCode()}"
} }
/**
* 伴生对象,提供工厂方法以及类型转换器的注册与查询功能。
*/
companion object { companion object {
/** /**
* 包装现有的 ByteBuffer * 包装现有的 ByteBuffer
@@ -279,6 +282,11 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
byteBufferWrapperConvertor byteBufferWrapperConvertor
} }
/**
* 添加转换器到映射表,通过具体化类型参数自动创建转换器实例
*
* @param T 转换器类型,必须提供无参构造函数
*/
@JvmName("inline_addConvertor") @JvmName("inline_addConvertor")
inline fun <reified T : ByteBufferWrapperConvertor<*>> addConvertor() { inline fun <reified T : ByteBufferWrapperConvertor<*>> addConvertor() {
addConvertor(ByteBufferWrapperConvertor.getInstantiation<T>()) addConvertor(ByteBufferWrapperConvertor.getInstantiation<T>())
@@ -537,24 +545,64 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
return convertor.read(this, parameters) return convertor.read(this, parameters)
} }
/**
* 从缓冲区中读取指定类型的对象(不带额外参数)
*
* @param clazz 要读取的对象类型对应的 Class 对象
* @param T 要读取的对象类型
* @return 读取并转换后的 T 类型对象
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
*/
fun <T : Any> getObject(clazz: Class<T>): T { fun <T : Any> getObject(clazz: Class<T>): T {
return getObject(clazz, emptyArray()) return getObject(clazz, emptyArray())
} }
/**
* 从缓冲区中读取指定类型的对象,并传入长度参数
*
* @param clazz 要读取的对象类型对应的 Class 对象
* @param size 读取长度(如数组元素个数),作为转换器的第一个参数
* @param T 要读取的对象类型
* @return 读取并转换后的 T 类型对象
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
*/
fun <T : Any> getObject(clazz: Class<T>, size: Int): T { fun <T : Any> getObject(clazz: Class<T>, size: Int): T {
return getObject(clazz, arrayOf(size)) return getObject(clazz, arrayOf(size))
} }
/**
* 从缓冲区中读取具体化类型 T 的对象,并传入额外参数
*
* @param parameters 传递给转换器的参数数组
* @param T 要读取的对象类型
* @return 读取并转换后的 T 类型对象
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
*/
@JvmName("inline_getObject") @JvmName("inline_getObject")
inline fun <reified T : Any> getObject(parameters: Array<Any>): T { inline fun <reified T : Any> getObject(parameters: Array<Any>): T {
return getObject(T::class.java, parameters) return getObject(T::class.java, parameters)
} }
/**
* 从缓冲区中读取具体化类型 T 的对象,并传入长度参数
*
* @param size 读取长度(如数组元素个数),作为转换器的第一个参数
* @param T 要读取的对象类型
* @return 读取并转换后的 T 类型对象
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
*/
@JvmName("inline_getObject") @JvmName("inline_getObject")
inline fun <reified T : Any> getObject(size: Int): T { inline fun <reified T : Any> getObject(size: Int): T {
return getObject(T::class.java, size) return getObject(T::class.java, size)
} }
/**
* 从缓冲区中读取具体化类型 T 的对象(不带额外参数)
*
* @param T 要读取的对象类型
* @return 读取并转换后的 T 类型对象
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
*/
@JvmName("inline_getObject") @JvmName("inline_getObject")
inline fun <reified T : Any> getObject(): T { inline fun <reified T : Any> getObject(): T {
return getObject(T::class.java) return getObject(T::class.java)
@@ -574,11 +622,24 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
return this return this
} }
/**
* 按初始化函数生成指定长度的字节数组并写入缓冲区
*
* @param size 要生成并写入的字节数
* @param init 初始化函数,根据索引生成每个字节的值
* @return 当前对象(支持链式调用)
*/
fun putByteArray(size: Int, init: (Int) -> Byte): ByteBufferWrapper { fun putByteArray(size: Int, init: (Int) -> Byte): ByteBufferWrapper {
buffer.put(ByteArray(size, init)) buffer.put(ByteArray(size, init))
return this return this
} }
/**
* 将字符数组完整写入缓冲区(每个字符取低 8 位,1字节)
*
* @param charArray 要写入的字符数组
* @return 当前对象(支持链式调用)
*/
fun putCharArray(charArray: CharArray): ByteBufferWrapper { fun putCharArray(charArray: CharArray): ByteBufferWrapper {
putByteArray(charArray.size) { putByteArray(charArray.size) {
charArray[it].code.toByte() charArray[it].code.toByte()
@@ -586,6 +647,12 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
return this return this
} }
/**
* 读取指定长度的字符数组(每个字节转换为一个字符)
*
* @param size 要读取的字符数
* @return 读取的字符数组
*/
fun getCharArray(size: Int): CharArray { fun getCharArray(size: Int): CharArray {
return getByteArray(size).let { return getByteArray(size).let {
CharArray(it.size) { s -> CharArray(it.size) { s ->
@@ -594,52 +661,118 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
} }
} }
/**
* 将整数数组完整写入缓冲区(每个整数4字节)
*
* @param intArray 要写入的整数数组
* @return 当前对象(支持链式调用)
*/
fun putIntArray(intArray: IntArray): ByteBufferWrapper { fun putIntArray(intArray: IntArray): ByteBufferWrapper {
intArray.forEach(::putInt) intArray.forEach(::putInt)
return this return this
} }
/**
* 读取指定长度的整数数组
*
* @param size 要读取的整数个数
* @return 读取的整数数组
*/
fun getIntArray(size: Int): IntArray { fun getIntArray(size: Int): IntArray {
return IntArray(size) { getInt() } return IntArray(size) { getInt() }
} }
/**
* 将短整数数组完整写入缓冲区(每个短整数2字节)
*
* @param shortArray 要写入的短整数数组
* @return 当前对象(支持链式调用)
*/
fun putShortArray(shortArray: ShortArray): ByteBufferWrapper { fun putShortArray(shortArray: ShortArray): ByteBufferWrapper {
shortArray.forEach(::putShort) shortArray.forEach(::putShort)
return this return this
} }
/**
* 读取指定长度的短整数数组
*
* @param size 要读取的短整数个数
* @return 读取的短整数数组
*/
fun getShortArray(size: Int): ShortArray { fun getShortArray(size: Int): ShortArray {
return ShortArray(size) { getShort() } return ShortArray(size) { getShort() }
} }
/**
* 将长整数数组完整写入缓冲区(每个长整数8字节)
*
* @param longArray 要写入的长整数数组
* @return 当前对象(支持链式调用)
*/
fun putLongArray(longArray: LongArray): ByteBufferWrapper { fun putLongArray(longArray: LongArray): ByteBufferWrapper {
longArray.forEach(::putLong) longArray.forEach(::putLong)
return this return this
} }
/**
* 读取指定长度的长整数数组
*
* @param size 要读取的长整数个数
* @return 读取的长整数数组
*/
fun getLongArray(size: Int): LongArray { fun getLongArray(size: Int): LongArray {
return LongArray(size) { getLong() } return LongArray(size) { getLong() }
} }
/**
* 将双精度浮点数数组完整写入缓冲区(每个浮点数8字节)
*
* @param doubleArray 要写入的双精度浮点数数组
* @return 当前对象(支持链式调用)
*/
fun putDoubleArray(doubleArray: DoubleArray): ByteBufferWrapper { fun putDoubleArray(doubleArray: DoubleArray): ByteBufferWrapper {
doubleArray.forEach(::putDouble) doubleArray.forEach(::putDouble)
return this return this
} }
/**
* 读取指定长度的双精度浮点数数组
*
* @param size 要读取的双精度浮点数个数
* @return 读取的双精度浮点数数组
*/
fun getDoubleArray(size: Int): DoubleArray { fun getDoubleArray(size: Int): DoubleArray {
return DoubleArray(size) { getDouble() } return DoubleArray(size) { getDouble() }
} }
/**
* 将单精度浮点数数组完整写入缓冲区(每个浮点数4字节)
*
* @param floatArray 要写入的单精度浮点数数组
* @return 当前对象(支持链式调用)
*/
fun putFloatArray(floatArray: FloatArray): ByteBufferWrapper { fun putFloatArray(floatArray: FloatArray): ByteBufferWrapper {
floatArray.forEach(::putFloat) floatArray.forEach(::putFloat)
return this return this
} }
/**
* 读取指定长度的单精度浮点数数组
*
* @param size 要读取的单精度浮点数个数
* @return 读取的单精度浮点数数组
*/
fun getFloatArray(size: Int): FloatArray { fun getFloatArray(size: Int): FloatArray {
return FloatArray(size) { getFloat() } return FloatArray(size) { getFloat() }
} }
/**
* 将布尔数组完整写入缓冲区(每个布尔值1字节,true = 0x01,false = 0x00)
*
* @param booleanArray 要写入的布尔数组
* @return 当前对象(支持链式调用)
*/
fun putBooleanArray(booleanArray: BooleanArray): ByteBufferWrapper { fun putBooleanArray(booleanArray: BooleanArray): ByteBufferWrapper {
putByteArray(booleanArray.size) { putByteArray(booleanArray.size) {
if (booleanArray[it]) 0x01 else 0x00 if (booleanArray[it]) 0x01 else 0x00
@@ -647,6 +780,13 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
return this return this
} }
/**
* 读取指定长度的布尔数组
*
* @param size 要读取的布尔值个数
* @return 读取的布尔数组
* @throws IllegalArgumentException 如果读取到的字节值不是 0x00 或 0x01
*/
fun getBooleanArray(size: Int): BooleanArray { fun getBooleanArray(size: Int): BooleanArray {
return getByteArray(size).let { return getByteArray(size).let {
BooleanArray(it.size) { index -> BooleanArray(it.size) { index ->
@@ -33,21 +33,67 @@ import java.util.*
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import java.util.UUID as JUUID import java.util.UUID as JUUID
/**
* ByteBufferWrapper 类型转换器接口。
*
* 定义某种类型与 [ByteBufferWrapper] 之间的读写规则。
*
* @param T 该转换器处理的数据类型
*/
interface ByteBufferWrapperConvertorInterface<T : Any> { interface ByteBufferWrapperConvertorInterface<T : Any> {
/**
* 将对象写入缓冲区。
*
* @param obj 要写入的对象
* @param byteBufferWrapper 目标缓冲区包装器
*/
fun write(obj: T, byteBufferWrapper: ByteBufferWrapper) fun write(obj: T, byteBufferWrapper: ByteBufferWrapper)
/**
* 从缓冲区中读取对象。
*
* @param byteBufferWrapper 源缓冲区包装器
* @param parameters 读取时需要的额外参数(如数组长度)
* @return 读取并转换后的对象
*/
fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T
/**
* 获取该转换器处理的数据类型。
*
* @return 类型对应的 Class 对象
*/
fun getType(): Class<T> fun getType(): Class<T>
} }
/**
* ByteBufferWrapper 类型转换器抽象基类。
*
* 提供转换器实例的缓存创建以及默认转换器的注册功能。
*
* @param T 该转换器处理的数据类型
*/
abstract class ByteBufferWrapperConvertor<T : Any> : ByteBufferWrapperConvertorInterface<T> { abstract class ByteBufferWrapperConvertor<T : Any> : ByteBufferWrapperConvertorInterface<T> {
/**
* 返回包含所处理类型信息的字符串表示。
*/
override fun toString(): String { override fun toString(): String {
return "ByteBufferWrapperConvertor(type=${getType()})" return "ByteBufferWrapperConvertor(type=${getType()})"
} }
/**
* 伴生对象,管理转换器实例缓存并提供默认转换器安装方法。
*/
companion object { companion object {
private val _instantiations = private val _instantiations =
ConcurrentHashMap<Class<ByteBufferWrapperConvertor<*>>, ByteBufferWrapperConvertor<*>>() ConcurrentHashMap<Class<ByteBufferWrapperConvertor<*>>, ByteBufferWrapperConvertor<*>>()
/**
* 获取指定转换器类的实例,不存在时通过无参构造函数创建并缓存。
*
* @param clazz 转换器类对应的 Class 对象
* @return 缓存的或新创建的转换器实例
*/
@JvmStatic @JvmStatic
fun getInstantiation(clazz: Class<ByteBufferWrapperConvertor<*>>): ByteBufferWrapperConvertor<*> { fun getInstantiation(clazz: Class<ByteBufferWrapperConvertor<*>>): ByteBufferWrapperConvertor<*> {
return _instantiations.getOrPut(clazz) { return _instantiations.getOrPut(clazz) {
@@ -55,12 +101,23 @@ abstract class ByteBufferWrapperConvertor<T : Any> : ByteBufferWrapperConvertorI
} }
} }
/**
* 获取具体化类型 T 对应的转换器实例,不存在时创建并缓存。
*
* @param T 转换器类型,必须提供无参构造函数
* @return 缓存的或新创建的转换器实例
*/
@JvmStatic @JvmStatic
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
inline fun <reified T : ByteBufferWrapperConvertor<*>> getInstantiation(): ByteBufferWrapperConvertor<*> { inline fun <reified T : ByteBufferWrapperConvertor<*>> getInstantiation(): ByteBufferWrapperConvertor<*> {
return getInstantiation(T::class.java as Class<ByteBufferWrapperConvertor<*>>) return getInstantiation(T::class.java as Class<ByteBufferWrapperConvertor<*>>)
} }
/**
* 安装所有默认转换器。
*
* 将基础类型、大数、字符串、时间、UUID 及各类数组的转换器注册到 [ByteBufferWrapper]。
*/
fun defaultConvertorInstall() { fun defaultConvertorInstall() {
ByteBufferWrapper.addConvertor<BigDecimalBufferWrapperConvertor>() ByteBufferWrapper.addConvertor<BigDecimalBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<BigIntegerBufferWrapperConvertor>() ByteBufferWrapper.addConvertor<BigIntegerBufferWrapperConvertor>()
@@ -91,6 +148,16 @@ abstract class ByteBufferWrapperConvertor<T : Any> : ByteBufferWrapperConvertorI
} }
} }
/**
* 基于读写函数构造的通用对象转换器。
*
* 通过传入的写入函数、读取函数和类型信息实现转换逻辑,读取时忽略额外参数。
*
* @param T 该转换器处理的数据类型
* @param write 写入函数,将对象写入缓冲区
* @param read 读取函数,从缓冲区读取对象
* @param typer 该转换器处理的数据类型对应的 Class 对象
*/
abstract class ObjectBufferWrapperConvertor<T : Any>( abstract class ObjectBufferWrapperConvertor<T : Any>(
val write: ByteBufferWrapper.(obj: T) -> Unit, val write: ByteBufferWrapper.(obj: T) -> Unit,
val read: ByteBufferWrapper.() -> T, val read: ByteBufferWrapper.() -> T,
@@ -104,72 +171,84 @@ abstract class ObjectBufferWrapperConvertor<T : Any>(
} }
/** [Byte] 类型转换器,使用 putByte/getByte 读写。 */
class BytedBufferWrapperConvertor : ObjectBufferWrapperConvertor<Byte>( class BytedBufferWrapperConvertor : ObjectBufferWrapperConvertor<Byte>(
ByteBufferWrapper::putByte, ByteBufferWrapper::putByte,
ByteBufferWrapper::getByte, ByteBufferWrapper::getByte,
Byte::class.java, Byte::class.java,
) )
/** [Char] 类型转换器,使用 putChar/getChar 读写。 */
class CharBufferWrapperConvertor : ObjectBufferWrapperConvertor<Char>( class CharBufferWrapperConvertor : ObjectBufferWrapperConvertor<Char>(
ByteBufferWrapper::putChar, ByteBufferWrapper::putChar,
ByteBufferWrapper::getChar, ByteBufferWrapper::getChar,
Char::class.java, Char::class.java,
) )
/** [Short] 类型转换器,使用 putShort/getShort 读写。 */
class ShortBufferWrapperConvertor : ObjectBufferWrapperConvertor<Short>( class ShortBufferWrapperConvertor : ObjectBufferWrapperConvertor<Short>(
ByteBufferWrapper::putShort, ByteBufferWrapper::putShort,
ByteBufferWrapper::getShort, ByteBufferWrapper::getShort,
Short::class.java, Short::class.java,
) )
/** [Int] 类型转换器,使用 putInt/getInt 读写。 */
class IntBufferWrapperConvertor : ObjectBufferWrapperConvertor<Int>( class IntBufferWrapperConvertor : ObjectBufferWrapperConvertor<Int>(
ByteBufferWrapper::putInt, ByteBufferWrapper::putInt,
ByteBufferWrapper::getInt, ByteBufferWrapper::getInt,
Int::class.java, Int::class.java,
) )
/** [Long] 类型转换器,使用 putLong/getLong 读写。 */
class LongBufferWrapperConvertor : ObjectBufferWrapperConvertor<Long>( class LongBufferWrapperConvertor : ObjectBufferWrapperConvertor<Long>(
ByteBufferWrapper::putLong, ByteBufferWrapper::putLong,
ByteBufferWrapper::getLong, ByteBufferWrapper::getLong,
Long::class.java, Long::class.java,
) )
/** [Double] 类型转换器,使用 putDouble/getDouble 读写。 */
class DoubleBufferWrapperConvertor : ObjectBufferWrapperConvertor<Double>( class DoubleBufferWrapperConvertor : ObjectBufferWrapperConvertor<Double>(
ByteBufferWrapper::putDouble, ByteBufferWrapper::putDouble,
ByteBufferWrapper::getDouble, ByteBufferWrapper::getDouble,
Double::class.java, Double::class.java,
) )
/** [Float] 类型转换器,使用 putFloat/getFloat 读写。 */
class FloatBufferWrapperConvertor : ObjectBufferWrapperConvertor<Float>( class FloatBufferWrapperConvertor : ObjectBufferWrapperConvertor<Float>(
ByteBufferWrapper::putFloat, ByteBufferWrapper::putFloat,
ByteBufferWrapper::getFloat, ByteBufferWrapper::getFloat,
Float::class.java, Float::class.java,
) )
/** [BigInteger] 类型转换器,使用 putBigInteger/getBigInteger 读写。 */
class BigIntegerBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigInteger>( class BigIntegerBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigInteger>(
ByteBufferWrapper::putBigInteger, ByteBufferWrapper::putBigInteger,
ByteBufferWrapper::getBigInteger, ByteBufferWrapper::getBigInteger,
BigInteger::class.java, BigInteger::class.java,
) )
/** [BigDecimal] 类型转换器,使用 putBigDecimal/getBigDecimal 读写。 */
class BigDecimalBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigDecimal>( class BigDecimalBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigDecimal>(
ByteBufferWrapper::putBigDecimal, ByteBufferWrapper::putBigDecimal,
ByteBufferWrapper::getBigDecimal, ByteBufferWrapper::getBigDecimal,
BigDecimal::class.java, BigDecimal::class.java,
) )
/** [Boolean] 类型转换器,使用 putBoolean/getBoolean 读写。 */
class BooleanBufferWrapperConvertor : ObjectBufferWrapperConvertor<Boolean>( class BooleanBufferWrapperConvertor : ObjectBufferWrapperConvertor<Boolean>(
ByteBufferWrapper::putBoolean, ByteBufferWrapper::putBoolean,
ByteBufferWrapper::getBoolean, ByteBufferWrapper::getBoolean,
Boolean::class.java, Boolean::class.java,
) )
/** [String] 类型转换器,使用 putString/getString 读写。 */
class StringBufferWrapperConvertor : ObjectBufferWrapperConvertor<String>( class StringBufferWrapperConvertor : ObjectBufferWrapperConvertor<String>(
ByteBufferWrapper::putString, ByteBufferWrapper::putString,
ByteBufferWrapper::getString, ByteBufferWrapper::getString,
String::class.java, String::class.java,
) )
/** [ByteFlags] 类型转换器,使用 putFlag/getFlag 读写。 */
class ByteFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<ByteFlags>( class ByteFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<ByteFlags>(
ByteBufferWrapper::putFlag, ByteBufferWrapper::putFlag,
ByteBufferWrapper::getFlag, ByteBufferWrapper::getFlag,
@@ -177,42 +256,62 @@ class ByteFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<ByteFlags>(
) )
/** Java [JUUID] 类型转换器,使用 putUUID/getJUUID 读写。 */
class JUUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<JUUID>( class JUUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<JUUID>(
ByteBufferWrapper::putUUID, ByteBufferWrapper::putUUID,
ByteBufferWrapper::getJUUID, ByteBufferWrapper::getJUUID,
JUUID::class.java, JUUID::class.java,
) )
/** 自定义 [UUID] 类型转换器,使用 putUUID/getUUID 读写。 */
class UUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<UUID>( class UUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<UUID>(
ByteBufferWrapper::putUUID, ByteBufferWrapper::putUUID,
ByteBufferWrapper::getUUID, ByteBufferWrapper::getUUID,
UUID::class.java, UUID::class.java,
) )
/** [DateTime] 类型转换器,使用 putDateTime/getDateTime 读写。 */
class DateTimeFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<DateTime>( class DateTimeFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<DateTime>(
ByteBufferWrapper::putDateTime, ByteBufferWrapper::putDateTime,
ByteBufferWrapper::getDateTime, ByteBufferWrapper::getDateTime,
DateTime::class.java, DateTime::class.java,
) )
/** [LocalDateTime] 类型转换器,使用 putLocalDateTime/getLocalDateTime 读写。 */
class LocalDateTimeBufferWrapperConvertor : ObjectBufferWrapperConvertor<LocalDateTime>( class LocalDateTimeBufferWrapperConvertor : ObjectBufferWrapperConvertor<LocalDateTime>(
ByteBufferWrapper::putLocalDateTime, ByteBufferWrapper::putLocalDateTime,
ByteBufferWrapper::getLocalDateTime, ByteBufferWrapper::getLocalDateTime,
LocalDateTime::class.java, LocalDateTime::class.java,
) )
/** [Date] 类型转换器,使用 putDate/getDate 读写。 */
class DateBufferWrapperConvertor : ObjectBufferWrapperConvertor<Date>( class DateBufferWrapperConvertor : ObjectBufferWrapperConvertor<Date>(
ByteBufferWrapper::putDate, ByteBufferWrapper::putDate,
ByteBufferWrapper::getDate, ByteBufferWrapper::getDate,
Date::class.java, Date::class.java,
) )
/**
* 基于读写函数构造的通用数组转换器。
*
* 读取时要求额外参数的第一个元素为 Int 类型的数组长度。
*
* @param T 该转换器处理的数组类型
* @param write 写入函数,将数组写入缓冲区
* @param read 读取函数,按指定长度从缓冲区读取数组
* @param typer 该转换器处理的数组类型对应的 Class 对象
*/
abstract class ArrayBufferWrapperConvertor<T : Any>( abstract class ArrayBufferWrapperConvertor<T : Any>(
val write: ByteBufferWrapper.(obj: T) -> Unit, val write: ByteBufferWrapper.(obj: T) -> Unit,
val read: ByteBufferWrapper.(size: Int) -> T, val read: ByteBufferWrapper.(size: Int) -> T,
val typer: Class<T>, val typer: Class<T>,
) : ByteBufferWrapperConvertor<T>() { ) : ByteBufferWrapperConvertor<T>() {
override fun write(obj: T, byteBufferWrapper: ByteBufferWrapper) = write.invoke(byteBufferWrapper, obj) override fun write(obj: T, byteBufferWrapper: ByteBufferWrapper) = write.invoke(byteBufferWrapper, obj)
/**
* 从缓冲区读取数组,要求 parameters[0] 为 Int 类型的长度。
*
* @throws IllegalArgumentException 如果参数为空或第一个参数不是 Int
*/
override fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T { override fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T {
if (parameters.isEmpty()) { if (parameters.isEmpty()) {
throw IllegalArgumentException("parameters cannot be empty, must has a Int") throw IllegalArgumentException("parameters cannot be empty, must has a Int")
@@ -226,42 +325,49 @@ abstract class ArrayBufferWrapperConvertor<T : Any>(
override fun getType(): Class<T> = typer override fun getType(): Class<T> = typer
} }
/** [ByteArray] 类型转换器,使用 putByteArray/getByteArray 读写。 */
class ByteArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ByteArray>( class ByteArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ByteArray>(
ByteBufferWrapper::putByteArray, ByteBufferWrapper::putByteArray,
ByteBufferWrapper::getByteArray, ByteBufferWrapper::getByteArray,
ByteArray::class.java, ByteArray::class.java,
) )
/** [CharArray] 类型转换器,使用 putCharArray/getCharArray 读写。 */
class CharArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<CharArray>( class CharArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<CharArray>(
ByteBufferWrapper::putCharArray, ByteBufferWrapper::putCharArray,
ByteBufferWrapper::getCharArray, ByteBufferWrapper::getCharArray,
CharArray::class.java, CharArray::class.java,
) )
/** [ShortArray] 类型转换器,使用 putShortArray/getShortArray 读写。 */
class ShortArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ShortArray>( class ShortArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ShortArray>(
ByteBufferWrapper::putShortArray, ByteBufferWrapper::putShortArray,
ByteBufferWrapper::getShortArray, ByteBufferWrapper::getShortArray,
ShortArray::class.java, ShortArray::class.java,
) )
/** [IntArray] 类型转换器,使用 putIntArray/getIntArray 读写。 */
class IntArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<IntArray>( class IntArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<IntArray>(
ByteBufferWrapper::putIntArray, ByteBufferWrapper::putIntArray,
ByteBufferWrapper::getIntArray, ByteBufferWrapper::getIntArray,
IntArray::class.java, IntArray::class.java,
) )
/** [LongArray] 类型转换器,使用 putLongArray/getLongArray 读写。 */
class LongArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<LongArray>( class LongArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<LongArray>(
ByteBufferWrapper::putLongArray, ByteBufferWrapper::putLongArray,
ByteBufferWrapper::getLongArray, ByteBufferWrapper::getLongArray,
LongArray::class.java, LongArray::class.java,
) )
/** [FloatArray] 类型转换器,使用 putFloatArray/getFloatArray 读写。 */
class FloatArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<FloatArray>( class FloatArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<FloatArray>(
ByteBufferWrapper::putFloatArray, ByteBufferWrapper::putFloatArray,
ByteBufferWrapper::getFloatArray, ByteBufferWrapper::getFloatArray,
FloatArray::class.java, FloatArray::class.java,
) )
/** [DoubleArray] 类型转换器,使用 putDoubleArray/getDoubleArray 读写。 */
class DoubleArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<DoubleArray>( class DoubleArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<DoubleArray>(
ByteBufferWrapper::putDoubleArray, ByteBufferWrapper::putDoubleArray,
ByteBufferWrapper::getDoubleArray, ByteBufferWrapper::getDoubleArray,
@@ -269,6 +375,7 @@ class DoubleArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<DoubleArra
) )
/** [BooleanArray] 类型转换器,使用 putBooleanArray/getBooleanArray 读写。 */
class BooleanArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<BooleanArray>( class BooleanArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<BooleanArray>(
ByteBufferWrapper::putBooleanArray, ByteBufferWrapper::putBooleanArray,
ByteBufferWrapper::getBooleanArray, ByteBufferWrapper::getBooleanArray,
@@ -295,4 +295,12 @@ fun ByteBuffer.putVarInt(value: Int): ByteBuffer = this.putVarLong(value.toLong(
fun ByteBuffer.putVarShort(value: Short): ByteBuffer = this.putVarLong(value.toLong()) fun ByteBuffer.putVarShort(value: Short): ByteBuffer = this.putVarLong(value.toLong())
/**
* 将 [ByteBuffer] 中剩余的全部字节写入指定的输出流。
*
* 此操作会读取从当前位置到 limit 之间的所有字节,并推进 position。
*
* @param outputStream 目标输出流
* @throws IOException 如果写入过程中发生 I/O 错误
*/
fun ByteBuffer.writeStream(outputStream: OutputStream) = outputStream.write(this.toByteArray()) fun ByteBuffer.writeStream(outputStream: OutputStream) = outputStream.write(this.toByteArray())
@@ -26,23 +26,56 @@ import java.io.OutputStream
import java.io.Serializable import java.io.Serializable
import java.nio.ByteBuffer import java.nio.ByteBuffer
/**
* 可转换为字节数组的对象接口。
*
* 实现该接口的对象可以将自身序列化为字节数组,并支持写入输出流或 [ByteBuffer]。
*/
interface ByteConvertible : Serializable { interface ByteConvertible : Serializable {
/**
* 将当前对象转换为字节数组。
*
* @return 表示当前对象的字节数组
*/
fun toBytes(): ByteArray fun toBytes(): ByteArray
/**
* 将当前对象转换后的字节数组写入指定的输出流。
*
* @param outputStream 目标输出流
*/
fun writeToStream(outputStream: OutputStream) { fun writeToStream(outputStream: OutputStream) {
outputStream.write(toBytes()) outputStream.write(toBytes())
} }
/**
* 将当前对象转换后的字节数组写入指定的 [ByteBuffer]。
*
* @param byteBuffer 目标缓冲区
*/
fun putToByteBuffer(byteBuffer: ByteBuffer) { fun putToByteBuffer(byteBuffer: ByteBuffer) {
byteBuffer.put(toBytes()) byteBuffer.put(toBytes())
} }
/**
* 伴生对象,提供面向输出流和缓冲区的便捷扩展函数。
*/
companion object { companion object {
/**
* 将 [ByteConvertible] 对象写入当前输出流。
*
* @param byteConvertible 要写入的可转换对象
*/
fun OutputStream.write(byteConvertible: ByteConvertible) { fun OutputStream.write(byteConvertible: ByteConvertible) {
byteConvertible.writeToStream(this) byteConvertible.writeToStream(this)
} }
/**
* 将 [ByteConvertible] 对象写入当前 [ByteBuffer]。
*
* @param byteConvertible 要写入的可转换对象
*/
fun ByteBuffer.put(byteConvertible: ByteConvertible) { fun ByteBuffer.put(byteConvertible: ByteConvertible) {
byteConvertible.putToByteBuffer(this) byteConvertible.putToByteBuffer(this)
} }
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile ByteFlags.kt * CurrentFile ByteFlags.kt
* LastUpdate 2026-06-21 10:40:58 * LastUpdate 2026-11-16 21:35:04
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -64,7 +64,7 @@ data class ByteFlags(
* *
* @param byte 要解析的字节 * @param byte 要解析的字节
*/ */
fun fromByte(byte: Byte) { fun fromByte(byte: Byte): ByteFlags {
val value = byte.toInt() and 0xFF val value = byte.toInt() and 0xFF
b0 = (value and 0x01) != 0 b0 = (value and 0x01) != 0
b1 = (value and 0x02) != 0 b1 = (value and 0x02) != 0
@@ -74,6 +74,7 @@ data class ByteFlags(
b5 = (value and 0x20) != 0 b5 = (value and 0x20) != 0
b6 = (value and 0x40) != 0 b6 = (value and 0x40) != 0
b7 = (value and 0x80) != 0 b7 = (value and 0x80) != 0
return this
} }
/** /**
@@ -122,7 +123,7 @@ data class ByteFlags(
* @param value 要设置的布尔值 * @param value 要设置的布尔值
* @throws IndexOutOfBoundsException 如果索引不在 0~7 范围内 * @throws IndexOutOfBoundsException 如果索引不在 0~7 范围内
*/ */
operator fun set(index: Int, value: Boolean) { operator fun set(index: Int, value: Boolean): ByteFlags {
when (index) { when (index) {
0 -> b0 = value 0 -> b0 = value
1 -> b1 = value 1 -> b1 = value
@@ -134,12 +135,13 @@ data class ByteFlags(
7 -> b7 = value 7 -> b7 = value
else -> throw IndexOutOfBoundsException("索引必须在0-7之间") else -> throw IndexOutOfBoundsException("索引必须在0-7之间")
} }
return this
} }
/** /**
* 将所有 8 个位设置为 `true`。 * 将所有 8 个位设置为 `true`。
*/ */
fun setAll() { fun setAll(): ByteFlags {
b0 = true b0 = true
b1 = true b1 = true
b2 = true b2 = true
@@ -148,12 +150,14 @@ data class ByteFlags(
b5 = true b5 = true
b6 = true b6 = true
b7 = true b7 = true
return this
} }
/** /**
* 将所有 8 个位设置为 `false`。 * 将所有 8 个位设置为 `false`。
*/ */
fun clearAll() { fun clearAll(): ByteFlags {
b0 = false b0 = false
b1 = false b1 = false
b2 = false b2 = false
@@ -162,12 +166,14 @@ data class ByteFlags(
b5 = false b5 = false
b6 = false b6 = false
b7 = false b7 = false
return this
} }
/** /**
* 对所有位执行逻辑取反(true ↔ false)。 * 对所有位执行逻辑取反(true ↔ false)。
*/ */
fun toggleAll() { fun toggleAll(): ByteFlags {
b0 = !b0 b0 = !b0
b1 = !b1 b1 = !b1
b2 = !b2 b2 = !b2
@@ -176,6 +182,8 @@ data class ByteFlags(
b5 = !b5 b5 = !b5
b6 = !b6 b6 = !b6
b7 = !b7 b7 = !b7
return this
} }
/** /**
@@ -184,8 +192,9 @@ data class ByteFlags(
* @param index 要切换的位索引(0~7) * @param index 要切换的位索引(0~7)
* @throws IndexOutOfBoundsException 如果索引无效 * @throws IndexOutOfBoundsException 如果索引无效
*/ */
fun toggle(index: Int) { fun toggle(index: Int): ByteFlags {
this[index] = !this[index] this[index] = !this[index]
return this
} }
/** /**
@@ -304,7 +313,7 @@ data class ByteFlags(
* @param array 布尔数组(长度至少为 8) * @param array 布尔数组(长度至少为 8)
* @throws IllegalArgumentException 如果数组长度不足 8 * @throws IllegalArgumentException 如果数组长度不足 8
*/ */
fun fromBooleanArray(array: BooleanArray) { fun fromBooleanArray(array: BooleanArray): ByteFlags {
require(array.size >= 8) { "数组长度至少为8" } require(array.size >= 8) { "数组长度至少为8" }
b0 = array[0] b0 = array[0]
b1 = array[1] b1 = array[1]
@@ -314,6 +323,7 @@ data class ByteFlags(
b5 = array[5] b5 = array[5]
b6 = array[6] b6 = array[6]
b7 = array[7] b7 = array[7]
return this
} }
/** /**
@@ -403,6 +413,9 @@ data class ByteFlags(
return "ByteFlags(${toBinaryString()} = ${toHexString()})" return "ByteFlags(${toBinaryString()} = ${toHexString()})"
} }
/**
* 伴生对象,提供 [ByteFlags] 的多种静态工厂方法。
*/
companion object { companion object {
/** /**
* 创建一个所有位均为 `true` 的 [ByteFlags] 实例。 * 创建一个所有位均为 `true` 的 [ByteFlags] 实例。
@@ -434,7 +447,6 @@ data class ByteFlags(
fun fromBinaryString(binary: String): ByteFlags { fun fromBinaryString(binary: String): ByteFlags {
require(binary.length == 8) { "二进制字符串长度必须为8" } require(binary.length == 8) { "二进制字符串长度必须为8" }
require(binary.all { it == '0' || it == '1' }) { "二进制字符串只能包含0和1" } require(binary.all { it == '0' || it == '1' }) { "二进制字符串只能包含0和1" }
return ByteFlags( return ByteFlags(
binary[7] == '1', // b0 是最低位(对应字符串最后一位) binary[7] == '1', // b0 是最低位(对应字符串最后一位)
binary[6] == '1', binary[6] == '1',
@@ -447,6 +459,19 @@ data class ByteFlags(
) )
} }
/**
* 从布尔数组创建 [ByteFlags] 实例。
*
* 使用数组的前 8 个元素(索引 0~7),分别对应 b0~b7。
*
* @param booleanArray 布尔数组(长度至少为 8)
* @return 对应的 ByteFlags 实例
* @throws IllegalArgumentException 如果数组长度不足 8
*/
fun fromBooleanArray(booleanArray: BooleanArray): ByteFlags {
return ByteFlags().fromBooleanArray(booleanArray)
}
/** /**
* 从整数创建 [ByteFlags] 实例(仅使用低 8 位)。 * 从整数创建 [ByteFlags] 实例(仅使用低 8 位)。
* *
@@ -28,11 +28,24 @@ import com.mingliqiye.utils.json.api.JSONA
import java.io.* import java.io.*
/**
* 通过 Java 序列化机制对当前对象进行深克隆。
*
* @param T 对象类型,必须实现 [Serializable]
* @return 深克隆后的新对象
*/
@JvmName("_inline_deepClone") @JvmName("_inline_deepClone")
inline fun <reified T : Serializable> T.deepClone(): T { inline fun <reified T : Serializable> T.deepClone(): T {
return deepClone(this) return deepClone(this)
} }
/**
* 通过 JSON 序列化与反序列化对当前对象进行深克隆。
*
* @param T 对象类型
* @return 深克隆后的新对象
* @throws JsonException 如果 JSON 转换过程中发生异常
*/
inline fun <reified T> T.deepJsonClone(): T { inline fun <reified T> T.deepJsonClone(): T {
try { try {
return JSONA.convert(this as Any, this!!.javaClass) as T return JSONA.convert(this as Any, this!!.javaClass) as T
@@ -43,6 +56,16 @@ inline fun <reified T> T.deepJsonClone(): T {
} }
} }
/**
* 通过 Java 序列化机制对对象进行深克隆。
*
* 将对象序列化到内存后再反序列化,得到一个全新的对象副本。
*
* @param T 对象类型,必须实现 [Serializable]
* @param obj 要克隆的对象
* @return 深克隆后的新对象
* @throws RuntimeException 如果序列化或反序列化过程中发生 I/O 异常或类找不到
*/
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
fun <T : Serializable?> deepClone(obj: T): T { fun <T : Serializable?> deepClone(obj: T): T {
try { try {
@@ -987,6 +987,14 @@ inline fun <reified T> toArray(list: List<T>): Array<T> {
.toArray(T::class.java) .toArray(T::class.java)
} }
/**
* 将任意类型的 List 转换为指定类型的数组。
*
* @param T 元素类型
* @param list 输入的 List
* @param clazz 数组元素类型对应的 Class 对象
* @return 转换后的数组
*/
fun <T> toArray(list: List<T>, clazz: Class<T>): Array<T> { fun <T> toArray(list: List<T>, clazz: Class<T>): Array<T> {
return SuperStream.of<T>(list) return SuperStream.of<T>(list)
.toArray(clazz) .toArray(clazz)
@@ -39,6 +39,9 @@ class IsChanged<T> {
*/ */
private val atomicReferenceData: AtomicReference<T> = AtomicReference() private val atomicReferenceData: AtomicReference<T> = AtomicReference()
/**
* 无参构造函数,初始数据为 null
*/
constructor() constructor()
/** /**
@@ -63,6 +63,9 @@ private fun getGetterName(fieldName: String): String {
*/ */
open class ConfigurationProps { open class ConfigurationProps {
/**
* 伴生对象,提供根据命令行参数初始化配置类实例的静态方法。
*/
companion object { companion object {
/** /**
* 初始化配置类实例,并根据命令行参数填充其字段。 * 初始化配置类实例,并根据命令行参数填充其字段。
@@ -241,6 +244,9 @@ open class ConfigurationProps {
} }
} }
/**
* 打印配置项帮助信息,列出所有标注了 ConfigurationProp 且允许显示帮助的字段名称、类型和描述。
*/
fun printHelp() { fun printHelp() {
val fields = this::class.java.declaredFields val fields = this::class.java.declaredFields
val help = StringBuilder() val help = StringBuilder()
@@ -258,6 +264,9 @@ open class ConfigurationProps {
println(help) println(help)
} }
/**
* 当前配置对象所有声明字段的名称与值的映射。
*/
val fields: Map<String, Any?> val fields: Map<String, Any?>
get() { get() {
val fields = this::class.java.declaredFields val fields = this::class.java.declaredFields
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示编码或解码过程中发生的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class CodecException @JvmOverloads constructor( class CodecException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 JSON 内容为空时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class EmptyJsonException @JvmOverloads constructor( class EmptyJsonException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 HTTP 相关异常的基类,继承自 [MingLiUtilsBaseException]。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
open class HttpException @JvmOverloads constructor( open class HttpException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 HTTP URL 无效或处理失败时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
open class HttpUrlException @JvmOverloads constructor( open class HttpUrlException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 JSON 内容无效或不合法时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class InvalidJsonException @JvmOverloads constructor( class InvalidJsonException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 JSON 对象类型转换失败时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class JsonObjectCastException @JvmOverloads constructor( class JsonObjectCastException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -16,15 +16,39 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JsonParserException.kt * CurrentFile JsonParserException.kt
* LastUpdate 2026-10-11 16:53:41 * LastUpdate 2026-11-17 16:22:52
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 JSON 解析过程中发生的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class JsonParserException @JvmOverloads constructor( class JsonParserException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
enableSuppression: Boolean = false, enableSuppression: Boolean = false,
writableStackTrace: Boolean = true, writableStackTrace: Boolean = true,
) : JsonException(message, throwable, enableSuppression, writableStackTrace) ) : JsonException(message, throwable, enableSuppression, writableStackTrace)
/**
* 表示 JSON 格式不正确时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class JsonFormatException @JvmOverloads constructor(
message: String? = null,
throwable: Throwable? = null,
enableSuppression: Boolean = false,
writableStackTrace: Boolean = true,
) : JsonException(message, throwable, enableSuppression, writableStackTrace)
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示 JSON 数据类型不匹配时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class JsonTypeException @JvmOverloads constructor( class JsonTypeException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* mingli-utils 工具库所有异常的基类,继承自 [RuntimeException]。
*
* @param message 异常信息,默认为 null
* @param cause 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
open class MingLiUtilsBaseException @JvmOverloads constructor( open class MingLiUtilsBaseException @JvmOverloads constructor(
message: String? = null, message: String? = null,
cause: Throwable? = null, cause: Throwable? = null,
@@ -22,6 +22,14 @@
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/**
* 表示请求的资源未找到时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class NotFoundResourceException @JvmOverloads constructor( class NotFoundResourceException @JvmOverloads constructor(
message: String? = null, message: String? = null,
throwable: Throwable? = null, throwable: Throwable? = null,
@@ -24,151 +24,381 @@
package com.mingliqiye.utils.functions package com.mingliqiye.utils.functions
/**
* 对任意对象执行无参函数调用,执行完成后返回接收者自身。
*
* @param function 要执行的无参函数
* @return 接收者自身
*/
fun <T> T.with(function: Function): T = function.call().let { fun <T> T.with(function: Function): T = function.call().let {
this this
} }
/**
* 以接收者自身作为参数执行函数调用,执行完成后返回接收者自身。
*
* @param function 接收一个参数的函数,调用时传入接收者自身
* @return 接收者自身
*/
fun <T> T.with(function: P1Function<T>): T = function.call(this).let { fun <T> T.with(function: P1Function<T>): T = function.call(this).let {
this this
} }
/**
* 无参数且无返回值的函数式接口。
*/
@FunctionalInterface @FunctionalInterface
fun interface Function { fun interface Function {
/**
* 执行函数调用。
*/
fun call() fun call()
} }
/**
* 接收 1 个参数且无返回值的函数式接口。
*
* @param P 参数类型
*/
@FunctionalInterface @FunctionalInterface
fun interface P1Function<P> { fun interface P1Function<P> {
/**
* 执行函数调用。
*
* @param p 参数
*/
fun call(p: P) fun call(p: P)
} }
/**
* 无参数且带返回值的函数式接口。
*
* @param R 返回值类型
*/
@FunctionalInterface @FunctionalInterface
fun interface RFunction<R> { fun interface RFunction<R> {
/**
* 执行函数调用。
*
* @return 函数执行结果
*/
fun call(): R fun call(): R
} }
/**
* 接收 1 个参数且带返回值的函数式接口。
*
* @param P 参数类型
* @param R 返回值类型
*/
@FunctionalInterface @FunctionalInterface
fun interface P1RFunction<P, R> { fun interface P1RFunction<P, R> {
/**
* 执行函数调用。
*
* @param p 参数
* @return 函数执行结果
*/
fun call(p: P): R fun call(p: P): R
} }
/**
* 接收 2 个参数且无返回值的函数式接口。
*
* @param P 第 1 个参数类型
* @param P1 第 2 个参数类型
*/
@FunctionalInterface @FunctionalInterface
fun interface P2Function<P, P1> { fun interface P2Function<P, P1> {
/**
* 执行函数调用。
*
* @param p 第 1 个参数
* @param p1 第 2 个参数
*/
fun call(p: P, p1: P1) fun call(p: P, p1: P1)
} }
/**
* 接收 2 个参数且带返回值的函数式接口。
*
* @param P 第 1 个参数类型
* @param P1 第 2 个参数类型
* @param R 返回值类型
*/
@FunctionalInterface @FunctionalInterface
fun interface P2RFunction<P, P1, R> { fun interface P2RFunction<P, P1, R> {
/**
* 执行函数调用。
*
* @param p 第 1 个参数
* @param p1 第 2 个参数
* @return 函数执行结果
*/
fun call(p: P, p1: P1): R fun call(p: P, p1: P1): R
} }
/**
* 接收 3 个参数且无返回值的函数式接口,参数类型依次为 P、P1、P2。
*/
@FunctionalInterface @FunctionalInterface
fun interface P3Function<P, P1, P2> { fun interface P3Function<P, P1, P2> {
/**
* 执行函数调用,参数依次为 p、p1、p2。
*/
fun call(p: P, p1: P1, p2: P2) fun call(p: P, p1: P1, p2: P2)
} }
/**
* 接收 3 个参数且带返回值的函数式接口,参数类型依次为 P、P1、P2,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P3RFunction<P, P1, P2, R> { fun interface P3RFunction<P, P1, P2, R> {
/**
* 执行函数调用,参数依次为 p、p1、p2。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2): R fun call(p: P, p1: P1, p2: P2): R
} }
/**
* 接收 4 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P3。
*/
@FunctionalInterface @FunctionalInterface
fun interface P4Function<P, P1, P2, P3> { fun interface P4Function<P, P1, P2, P3> {
/**
* 执行函数调用,参数依次为 p、p1 至 p3。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3) fun call(p: P, p1: P1, p2: P2, p3: P3)
} }
/**
* 接收 4 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P3,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P4RFunction<P, P1, P2, P3, R> { fun interface P4RFunction<P, P1, P2, P3, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p3。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3): R fun call(p: P, p1: P1, p2: P2, p3: P3): R
} }
/**
* 接收 5 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P4。
*/
@FunctionalInterface @FunctionalInterface
fun interface P5Function<P, P1, P2, P3, P4> { fun interface P5Function<P, P1, P2, P3, P4> {
/**
* 执行函数调用,参数依次为 p、p1 至 p4。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4)
} }
/**
* 接收 5 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P4,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P5RFunction<P, P1, P2, P3, P4, R> { fun interface P5RFunction<P, P1, P2, P3, P4, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p4。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4): R
} }
/**
* 接收 6 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P5。
*/
@FunctionalInterface @FunctionalInterface
fun interface P6Function<P, P1, P2, P3, P4, P5> { fun interface P6Function<P, P1, P2, P3, P4, P5> {
/**
* 执行函数调用,参数依次为 p、p1 至 p5。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5)
} }
/**
* 接收 6 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P5,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P6RFunction<P, P1, P2, P3, P4, P5, R> { fun interface P6RFunction<P, P1, P2, P3, P4, P5, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p5。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): R
} }
/**
* 接收 7 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P6。
*/
@FunctionalInterface @FunctionalInterface
fun interface P7Function<P, P1, P2, P3, P4, P5, P6> { fun interface P7Function<P, P1, P2, P3, P4, P5, P6> {
/**
* 执行函数调用,参数依次为 p、p1 至 p6。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6)
} }
/**
* 接收 7 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P6,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P7RFunction<P, P1, P2, P3, P4, P5, P6, R> { fun interface P7RFunction<P, P1, P2, P3, P4, P5, P6, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p6。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): R
} }
/**
* 接收 8 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P7。
*/
@FunctionalInterface @FunctionalInterface
fun interface P8Function<P, P1, P2, P3, P4, P5, P6, P7> { fun interface P8Function<P, P1, P2, P3, P4, P5, P6, P7> {
/**
* 执行函数调用,参数依次为 p、p1 至 p7。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7)
} }
/**
* 接收 8 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P7,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P8RFunction<P, P1, P2, P3, P4, P5, P6, P7, R> { fun interface P8RFunction<P, P1, P2, P3, P4, P5, P6, P7, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p7。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7): R
} }
/**
* 接收 9 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P8。
*/
@FunctionalInterface @FunctionalInterface
fun interface P9Function<P, P1, P2, P3, P4, P5, P6, P7, P8> { fun interface P9Function<P, P1, P2, P3, P4, P5, P6, P7, P8> {
/**
* 执行函数调用,参数依次为 p、p1 至 p8。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8)
} }
/**
* 接收 9 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P8,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P9RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, R> { fun interface P9RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p8。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8): R
} }
/**
* 接收 10 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P9。
*/
@FunctionalInterface @FunctionalInterface
fun interface P10Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9> { fun interface P10Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9> {
/**
* 执行函数调用,参数依次为 p、p1 至 p9。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9)
} }
/**
* 接收 10 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P9,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P10RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, R> { fun interface P10RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p9。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9): R
} }
/**
* 接收 11 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P10。
*/
@FunctionalInterface @FunctionalInterface
fun interface P11Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10> { fun interface P11Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10> {
/**
* 执行函数调用,参数依次为 p、p1 至 p10。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10)
} }
/**
* 接收 11 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P10,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P11RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> { fun interface P11RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p10。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10): R
} }
/**
* 接收 12 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P11。
*/
@FunctionalInterface @FunctionalInterface
fun interface P12Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11> { fun interface P12Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11> {
/**
* 执行函数调用,参数依次为 p、p1 至 p11。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11)
} }
/**
* 接收 12 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P11,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P12RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R> { fun interface P12RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p11。
*
* @return 函数执行结果
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11): R fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11): R
} }
/**
* 接收 13 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P12。
*/
@FunctionalInterface @FunctionalInterface
fun interface P13Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12> { fun interface P13Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12> {
/**
* 执行函数调用,参数依次为 p、p1 至 p12。
*/
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12) fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12)
} }
/**
* 接收 13 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P12,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P13RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> { fun interface P13RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p12。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -186,8 +416,14 @@ fun interface P13RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
): R ): R
} }
/**
* 接收 14 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P13。
*/
@FunctionalInterface @FunctionalInterface
fun interface P14Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13> { fun interface P14Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13> {
/**
* 执行函数调用,参数依次为 p、p1 至 p13。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -206,8 +442,16 @@ fun interface P14Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
) )
} }
/**
* 接收 14 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P13,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P14RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> { fun interface P14RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p13。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -226,8 +470,14 @@ fun interface P14RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
): R ): R
} }
/**
* 接收 15 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P14。
*/
@FunctionalInterface @FunctionalInterface
fun interface P15Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14> { fun interface P15Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14> {
/**
* 执行函数调用,参数依次为 p、p1 至 p14。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -247,8 +497,16 @@ fun interface P15Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
) )
} }
/**
* 接收 15 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P14,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P15RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R> { fun interface P15RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p14。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -268,8 +526,14 @@ fun interface P15RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
): R ): R
} }
/**
* 接收 16 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P15。
*/
@FunctionalInterface @FunctionalInterface
fun interface P16Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15> { fun interface P16Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15> {
/**
* 执行函数调用,参数依次为 p、p1 至 p15。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -290,8 +554,16 @@ fun interface P16Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
) )
} }
/**
* 接收 16 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P15,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P16RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R> { fun interface P16RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p15。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -312,8 +584,14 @@ fun interface P16RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
): R ): R
} }
/**
* 接收 17 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P16。
*/
@FunctionalInterface @FunctionalInterface
fun interface P17Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16> { fun interface P17Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16> {
/**
* 执行函数调用,参数依次为 p、p1 至 p16。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -335,8 +613,16 @@ fun interface P17Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
) )
} }
/**
* 接收 17 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P16,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P17RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R> { fun interface P17RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p16。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -358,8 +644,14 @@ fun interface P17RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
): R ): R
} }
/**
* 接收 18 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P17。
*/
@FunctionalInterface @FunctionalInterface
fun interface P18Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17> { fun interface P18Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17> {
/**
* 执行函数调用,参数依次为 p、p1 至 p17。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -382,8 +674,16 @@ fun interface P18Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
) )
} }
/**
* 接收 18 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P17,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P18RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, R> { fun interface P18RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p17。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -406,8 +706,14 @@ fun interface P18RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
): R ): R
} }
/**
* 接收 19 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P18。
*/
@FunctionalInterface @FunctionalInterface
fun interface P19Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18> { fun interface P19Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18> {
/**
* 执行函数调用,参数依次为 p、p1 至 p18。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -431,8 +737,16 @@ fun interface P19Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
) )
} }
/**
* 接收 19 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P18,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P19RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, R> { fun interface P19RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p18。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -456,8 +770,14 @@ fun interface P19RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
): R ): R
} }
/**
* 接收 20 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P19。
*/
@FunctionalInterface @FunctionalInterface
fun interface P20Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19> { fun interface P20Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19> {
/**
* 执行函数调用,参数依次为 p、p1 至 p19。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -482,8 +802,16 @@ fun interface P20Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
) )
} }
/**
* 接收 20 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P19,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P20RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R> { fun interface P20RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p19。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -508,8 +836,14 @@ fun interface P20RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
): R ): R
} }
/**
* 接收 21 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P20。
*/
@FunctionalInterface @FunctionalInterface
fun interface P21Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20> { fun interface P21Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20> {
/**
* 执行函数调用,参数依次为 p、p1 至 p20。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -535,8 +869,16 @@ fun interface P21Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
) )
} }
/**
* 接收 21 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P20,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P21RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, R> { fun interface P21RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p20。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -562,8 +904,14 @@ fun interface P21RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
): R ): R
} }
/**
* 接收 22 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P21。
*/
@FunctionalInterface @FunctionalInterface
fun interface P22Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21> { fun interface P22Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21> {
/**
* 执行函数调用,参数依次为 p、p1 至 p21。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -590,8 +938,16 @@ fun interface P22Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
) )
} }
/**
* 接收 22 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P21,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P22RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, R> { fun interface P22RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p21。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -618,8 +974,14 @@ fun interface P22RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
): R ): R
} }
/**
* 接收 23 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P22。
*/
@FunctionalInterface @FunctionalInterface
fun interface P23Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22> { fun interface P23Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22> {
/**
* 执行函数调用,参数依次为 p、p1 至 p22。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -647,8 +1009,16 @@ fun interface P23Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
) )
} }
/**
* 接收 23 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P22,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P23RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, R> { fun interface P23RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p22。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -676,8 +1046,14 @@ fun interface P23RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
): R ): R
} }
/**
* 接收 24 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P23。
*/
@FunctionalInterface @FunctionalInterface
fun interface P24Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23> { fun interface P24Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23> {
/**
* 执行函数调用,参数依次为 p、p1 至 p23。
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -706,8 +1082,16 @@ fun interface P24Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
) )
} }
/**
* 接收 24 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P23,返回值类型为 R。
*/
@FunctionalInterface @FunctionalInterface
fun interface P24RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, R> { fun interface P24RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, R> {
/**
* 执行函数调用,参数依次为 p、p1 至 p23。
*
* @return 函数执行结果
*/
fun call( fun call(
p: P, p: P,
p1: P1, p1: P1,
@@ -22,10 +22,22 @@
package com.mingliqiye.utils.http package com.mingliqiye.utils.http
/**
* HTTP 响应基类,封装时间、消息、数据和状态码等通用响应字段。
*
* 除 [time] 外字段均可变,本身非线程安全;
* 如需不可变更新语义,请使用子类的 with* 系列方法。
*
* @param T 响应数据的类型
*/
open class BaseResponse<T>( open class BaseResponse<T>(
/** 响应时间(格式化的字符串),创建后不可修改 */
open val time: String, open val time: String,
/** 响应消息,可通过 setter 修改 */
open var message: String, open var message: String,
/** 响应数据,可通过 setter 修改 */
open var data: T, open var data: T,
/** HTTP 状态码,可通过 setter 修改 */
open var statusCode: Int, open var statusCode: Int,
) { ) {
File diff suppressed because it is too large Load Diff
@@ -26,4 +26,9 @@ package com.mingliqiye.utils.http
import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaType
/**
* 将本枚举转换为 OkHttp 的 [okhttp3.MediaType]。
*
* @return 与 [MediaType.value] 对应的 OkHttp 媒体类型
*/
fun MediaType.okhttp(): okhttp3.MediaType = this.value.toMediaType() fun MediaType.okhttp(): okhttp3.MediaType = this.value.toMediaType()
@@ -53,7 +53,15 @@ data class PageData<T>(
*/ */
val pageIndex: Long = 0, val pageIndex: Long = 0,
) { ) {
/** 伴生对象,提供工厂方法 */
companion object { companion object {
/**
* 从 MyBatis-Plus 的分页对象构建分页数据
*
* @param T 记录类型
* @param page MyBatis-Plus 分页对象
* @return 转换后的分页数据
*/
fun <T> of(page: Page<T>): PageData<T> = PageData( fun <T> of(page: Page<T>): PageData<T> = PageData(
records = page.records, records = page.records,
totalCount = page.total, totalCount = page.total,
@@ -25,6 +25,18 @@ package com.mingliqiye.utils.http
import com.baomidou.mybatisplus.extension.plugins.pagination.Page import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.mingliqiye.utils.time.DateTime import com.mingliqiye.utils.time.DateTime
/**
* 分页 HTTP 响应数据类,数据部分为 [PageData] 分页结构。
*
* 继承 [BaseResponse],支持链式调用与 with* 不可变更新,
* 并提供多种工厂方法创建成功/错误响应。
*
* @param T 分页记录的类型
* @property time 响应时间(格式化的字符串)
* @property message 响应消息
* @property data 分页响应数据
* @property statusCode HTTP 状态码
*/
data class PagedResponse<T>( data class PagedResponse<T>(
override val time: String, // 响应时间,一旦创建不可修改 override val time: String, // 响应时间,一旦创建不可修改
override var message: String, // 响应消息,可通过setter修改 override var message: String, // 响应消息,可通过setter修改
@@ -36,6 +48,7 @@ data class PagedResponse<T>(
data, data,
statusCode statusCode
) { ) {
/** 伴生对象,提供各类分页响应的工厂方法 */
companion object { companion object {
/** /**
* 创建一个默认的成功响应对象 * 创建一个默认的成功响应对象
@@ -49,6 +49,7 @@ data class Response<T>(
statusCode, statusCode,
) { ) {
/** 伴生对象,提供各类响应的工厂方法 */
companion object { companion object {
/** /**
* 创建一个默认的成功响应对象 * 创建一个默认的成功响应对象
@@ -300,6 +300,23 @@ enum class Method {
} }
/**
* 在 [Request.Builder] 上设置 POST 方法,使用空请求体。
*
* @return 当前 [Request.Builder],便于链式调用
*/
fun Request.Builder.post() = post(RequestBody.EMPTY) fun Request.Builder.post() = post(RequestBody.EMPTY)
/**
* 在 [Request.Builder] 上设置 PUT 方法,使用空请求体。
*
* @return 当前 [Request.Builder],便于链式调用
*/
fun Request.Builder.put() = put(RequestBody.EMPTY) fun Request.Builder.put() = put(RequestBody.EMPTY)
/**
* 在 [Request.Builder] 上设置 PATCH 方法,使用空请求体。
*
* @return 当前 [Request.Builder],便于链式调用
*/
fun Request.Builder.patch() = patch(RequestBody.EMPTY) fun Request.Builder.patch() = patch(RequestBody.EMPTY)
@@ -28,16 +28,37 @@ import java.io.OutputStream
import java.nio.charset.Charset import java.nio.charset.Charset
/**
* 读取输入流中的全部字节并按指定字符集解码为字符串。
*
* @param charset 字符编码,默认为 [Charsets.UTF_8]
* @return 解码后的字符串
*/
fun InputStream.readAllText(charset: Charset = Charsets.UTF_8) = this.readAllBytes().toString(charset) fun InputStream.readAllText(charset: Charset = Charsets.UTF_8) = this.readAllBytes().toString(charset)
/**
* 将输入流中的全部字节导出到指定输出流,并刷新输出流。
*
* @param out 目标输出流
*/
fun InputStream.exportBytes(out: OutputStream) { fun InputStream.exportBytes(out: OutputStream) {
out.write(this.readAllBytes()) out.write(this.readAllBytes())
out.flush() out.flush()
} }
/**
* 读取输入流中的全部字节并转换为字节列表。
*
* @return 包含全部字节的列表
*/
fun InputStream.readToList(): List<Byte> = this.readBytes().toList() fun InputStream.readToList(): List<Byte> = this.readBytes().toList()
/**
* 读取输入流中的全部字节。
*
* @return 包含全部字节的字节数组
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER") @Suppress("EXTENSION_SHADOWED_BY_MEMBER")
@JvmName("readInputStreamAllBytes") @JvmName("readInputStreamAllBytes")
fun InputStream.readAllBytes(): ByteArray = this.readBytes() fun InputStream.readAllBytes(): ByteArray = this.readBytes()
@@ -44,10 +44,24 @@ object SIO {
return this return this
} }
/**
* 扩展函数:条件不满足时对当前对象执行给定变换函数
*
* @param boolean 条件值,为 true 时直接返回原对象
* @param pd 条件为 false 时执行的变换函数
* @return 原对象或变换后的对象
*/
fun <T> T.ifOr(boolean: Boolean, pd: T.() -> T): T = if (boolean) { fun <T> T.ifOr(boolean: Boolean, pd: T.() -> T): T = if (boolean) {
this this
} else pd(this) } else pd(this)
/**
* 扩展函数:条件满足时对当前对象执行给定变换函数
*
* @param boolean 条件值,为 false 时直接返回原对象
* @param pd 条件为 true 时执行的变换函数
* @return 原对象或变换后的对象
*/
fun <T> T.ifOrElse(boolean: Boolean, pd: T.() -> T): T = if (!boolean) { fun <T> T.ifOrElse(boolean: Boolean, pd: T.() -> T): T = if (!boolean) {
this this
} else pd(this) } else pd(this)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JSONA.kt * CurrentFile JSONA.kt
* LastUpdate 2026-11-07 13:29:54 * LastUpdate 2026-11-17 19:59:21
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -29,8 +29,6 @@ import com.mingliqiye.utils.json.api.JSONA.setJsonApi
import com.mingliqiye.utils.json.api.base.JsonApi import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.type.JsonTypeReference import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.api.type.listType import com.mingliqiye.utils.json.api.type.listType
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJsonConverter
import com.mingliqiye.utils.json.objects.base.JsonItem import com.mingliqiye.utils.json.objects.base.JsonItem
import java.io.File import java.io.File
import java.io.IOException import java.io.IOException
@@ -522,21 +520,6 @@ object JSONA {
fun <D> convert(source: Any, destinationType: JsonTypeReference<D>): D = fun <D> convert(source: Any, destinationType: JsonTypeReference<D>): D =
jsonApi.convert(source, destinationType) jsonApi.convert(source, destinationType)
/**
* 添加 JSON 转换器到 API 中。
*
* @param c 需要添加的 [BaseJsonConverter] 实例
*/
@JvmStatic
fun addJsonConverter(c: BaseJsonConverter<*, *>) = jsonApi.addJsonConverter(c)
/**
* 使用反射创建并添加指定类型的 JSON 转换器到 API 中。
*
* @param T 继承自 [BaseJsonConverter] 的具体实现类
*/
inline fun <reified T : BaseJsonConverter<*, *>> addJsonConverter() = addJsonConverter(getJsonConverter<T>())
/** /**
* 将当前字符串解析为指定泛型类型的对象。 * 将当前字符串解析为指定泛型类型的对象。
* *
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile Jackson3JsonApi.kt * CurrentFile Jackson3JsonApi.kt
* LastUpdate 2026-10-12 13:59:59 * LastUpdate 2026-11-17 19:59:59
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -26,8 +26,6 @@ import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.api.JackSon3JsonItem.Companion.getJsonItem import com.mingliqiye.utils.json.api.JackSon3JsonItem.Companion.getJsonItem
import com.mingliqiye.utils.json.api.base.JsonApi import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.type.JsonTypeReference import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJackson3Module
import com.mingliqiye.utils.json.objects.base.* import com.mingliqiye.utils.json.objects.base.*
import tools.jackson.core.type.TypeReference import tools.jackson.core.type.TypeReference
import tools.jackson.databind.JsonNode import tools.jackson.databind.JsonNode
@@ -36,22 +34,48 @@ import tools.jackson.databind.node.JsonNodeType
import tools.jackson.databind.node.ObjectNode import tools.jackson.databind.node.ObjectNode
import java.lang.reflect.Type import java.lang.reflect.Type
/**
* 基于Jackson3的JSON处理实现类,提供JSON字符串解析、格式化、合并、节点操作等功能。
*
* 节点路径操作([getNodeValue]、[updateNodeValue])使用JSON Pointer风格路径(如"/user/name")。
* ObjectMapper支持直接持有,也支持通过get/set回调间接访问外部实例。
*/
class Jackson3JsonApi : JsonApi { class Jackson3JsonApi : JsonApi {
/**
* ObjectMapper的获取回调,默认返回内部持有的实例
*/
var get: () -> ObjectMapper = { _prObjectMapper!! } var get: () -> ObjectMapper = { _prObjectMapper!! }
/**
* ObjectMapper的设置回调,默认写入内部持有的实例
*/
var set: (ObjectMapper) -> Unit = { _prObjectMapper = it } var set: (ObjectMapper) -> Unit = { _prObjectMapper = it }
private var _prObjectMapper: ObjectMapper? = null private var _prObjectMapper: ObjectMapper? = null
/**
* 当前使用的ObjectMapper实例,读写均通过[get]/[set]回调转发
*/
var objectMapper: ObjectMapper var objectMapper: ObjectMapper
get() = get() get() = get()
private set(value) = set(value) private set(value) = set(value)
/**
* 使用指定的ObjectMapper构造实例
*
* @param objectMapper 自定义的ObjectMapper实例
*/
constructor(objectMapper: ObjectMapper) { constructor(objectMapper: ObjectMapper) {
_prObjectMapper = objectMapper _prObjectMapper = objectMapper
} }
/**
* 使用获取/设置回调构造实例,ObjectMapper由外部管理
*
* @param get ObjectMapper的获取回调
* @param set ObjectMapper的设置回调
*/
constructor( constructor(
get: () -> ObjectMapper, get: () -> ObjectMapper,
set: (ObjectMapper) -> Unit, set: (ObjectMapper) -> Unit,
@@ -60,6 +84,9 @@ class Jackson3JsonApi : JsonApi {
this.set = set this.set = set
} }
/**
* 使用默认的ObjectMapper构造实例
*/
constructor() { constructor() {
_prObjectMapper = ObjectMapper() _prObjectMapper = ObjectMapper()
} }
@@ -107,6 +134,9 @@ class Jackson3JsonApi : JsonApi {
} }
} }
/**
* 合并多个JSON对象字符串;无参数时返回"{}",遇到非对象JSON时抛出JsonException
*/
override fun merge(vararg jsons: String): String { override fun merge(vararg jsons: String): String {
try { try {
if (jsons.isEmpty()) return "{}" if (jsons.isEmpty()) return "{}"
@@ -128,6 +158,9 @@ class Jackson3JsonApi : JsonApi {
} }
} }
/**
* 获取指定路径的节点值,路径为JSON Pointer风格(如"/user/name"),节点缺失或为null时返回null
*/
override fun getNodeValue(json: String, path: String): String? { override fun getNodeValue(json: String, path: String): String? {
try { try {
val rootNode = objectMapper.readTree(json) val rootNode = objectMapper.readTree(json)
@@ -143,6 +176,9 @@ class Jackson3JsonApi : JsonApi {
} }
} }
/**
* 更新指定路径的节点值,路径为JSON Pointer风格(如"/user/name"),空路径时替换整个根节点
*/
override fun updateNodeValue(json: String, path: String, newValue: Any): String { override fun updateNodeValue(json: String, path: String, newValue: Any): String {
try { try {
val rootNode = objectMapper.readTree(json) val rootNode = objectMapper.readTree(json)
@@ -213,12 +249,10 @@ class Jackson3JsonApi : JsonApi {
return current return current
} }
override fun addJsonConverter(c: BaseJsonConverter<*, *>) {
val mapperBuilder = Jackson3ApiJavaHelper.rebuild(objectMapper)
mapperBuilder.addModule(c.getJackson3Module())
this.objectMapper = mapperBuilder.build()
}
/**
* 将JSON字符串解析为JsonItem对象,解析失败时包装为JsonException抛出
*/
override fun parseJsonItem(json: String): JsonItem { override fun parseJsonItem(json: String): JsonItem {
try { try {
return getJsonItem(objectMapper.readTree(json)) return getJsonItem(objectMapper.readTree(json))
@@ -229,8 +263,21 @@ class Jackson3JsonApi : JsonApi {
} }
/**
* 基于Jackson3的JsonItem标记实现类,通过伴生对象工厂方法创建具体的JsonItem
*/
class JackSon3JsonItem : JsonItem { class JackSon3JsonItem : JsonItem {
/**
* 伴生对象,提供JsonNode到JsonItem的工厂方法
*/
companion object { companion object {
/**
* 根据JsonNode的节点类型创建对应的JsonItem实例
*
* @param node Jackson3的JsonNode节点
* @return 与节点类型对应的JsonItem实例
* @throws IllegalStateException 当节点类型未知时抛出
*/
fun getJsonItem(node: JsonNode): JsonItem { fun getJsonItem(node: JsonNode): JsonItem {
return when (node.nodeType) { return when (node.nodeType) {
JsonNodeType.OBJECT -> JackSon3JsonObject(node) JsonNodeType.OBJECT -> JackSon3JsonObject(node)
@@ -245,11 +292,31 @@ class JackSon3JsonItem : JsonItem {
} }
} }
/**
* 基于Jackson3节点的JSON数字类型
*
* @param node 数字类型的JsonNode节点
*/
class JackSon3JsonNumber(node: JsonNode) : JsonNumber(node.asString()) class JackSon3JsonNumber(node: JsonNode) : JsonNumber(node.asString())
/**
* 基于Jackson3节点的JSON布尔类型
*
* @param node 布尔类型的JsonNode节点
*/
class JackSon3JsonBoolean(node: JsonNode) : JsonBoolean(node.asBoolean()) class JackSon3JsonBoolean(node: JsonNode) : JsonBoolean(node.asBoolean())
/**
* 基于Jackson3节点的JSON字符串类型
*
* @param node 字符串类型的JsonNode节点
*/
class JackSon3JsonString(node: JsonNode) : JsonString(node.asString()) class JackSon3JsonString(node: JsonNode) : JsonString(node.asString())
/**
* 基于Jackson3节点的JSON数组类型
*
* @property node 数组类型的JsonNode节点
*/
class JackSon3JsonArray(val node: JsonNode) : JsonArray() { class JackSon3JsonArray(val node: JsonNode) : JsonArray() {
override fun getIndex(index: Int): JsonItem { override fun getIndex(index: Int): JsonItem {
return JackSon3JsonItem.getJsonItem(node.get(index)) return JackSon3JsonItem.getJsonItem(node.get(index))
@@ -271,6 +338,11 @@ class JackSon3JsonArray(val node: JsonNode) : JsonArray() {
} }
} }
/**
* 基于Jackson3节点的JSON对象类型
*
* @property node 对象类型的JsonNode节点
*/
class JackSon3JsonObject(val node: JsonNode) : JsonObject() { class JackSon3JsonObject(val node: JsonNode) : JsonObject() {
override fun getField(name: String): JsonItem { override fun getField(name: String): JsonItem {
return JackSon3JsonItem.getJsonItem(node.get(name)) return JackSon3JsonItem.getJsonItem(node.get(name))
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JacksonJsonApi.kt * CurrentFile JacksonJsonApi.kt
* LastUpdate 2026-10-12 10:48:31 * LastUpdate 2026-11-17 19:59:59
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -33,8 +33,6 @@ import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.api.JackSonJsonItem.Companion.getJsonItem import com.mingliqiye.utils.json.api.JackSonJsonItem.Companion.getJsonItem
import com.mingliqiye.utils.json.api.base.JsonApi import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.type.JsonTypeReference import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJacksonModule
import com.mingliqiye.utils.json.objects.base.* import com.mingliqiye.utils.json.objects.base.*
/** /**
@@ -51,6 +49,11 @@ class JacksonJsonApi : JsonApi {
this.objectMapper = ObjectMapper() this.objectMapper = ObjectMapper()
} }
/**
* 获取内部使用的ObjectMapper实例
*
* @return 当前的ObjectMapper实例
*/
fun getObjectMapper() = objectMapper fun getObjectMapper() = objectMapper
/** /**
@@ -115,6 +118,13 @@ class JacksonJsonApi : JsonApi {
} }
} }
/**
* 将对象格式化为JSON字符串,非ASCII字符以Unicode转义形式输出
*
* @param obj 待格式化的对象
* @return 格式化后的JSON字符串
* @throws JsonException 当格式化失败时抛出异常
*/
fun formatUnicode(obj: Any): String { fun formatUnicode(obj: Any): String {
return try { return try {
objectMapper.writer().with(JsonGenerator.Feature.ESCAPE_NON_ASCII).writeValueAsString(obj) objectMapper.writer().with(JsonGenerator.Feature.ESCAPE_NON_ASCII).writeValueAsString(obj)
@@ -139,6 +149,13 @@ class JacksonJsonApi : JsonApi {
} }
} }
/**
* 将对象格式化为美化(带缩进)的JSON字符串,非ASCII字符以Unicode转义形式输出
*
* @param obj 待格式化的对象
* @return 美化后的JSON字符串
* @throws JsonException 当格式化失败时抛出异常
*/
fun formatPrettyUnicode(obj: Any): String { fun formatPrettyUnicode(obj: Any): String {
return try { return try {
objectMapper.writerWithDefaultPrettyPrinter().with(JsonGenerator.Feature.ESCAPE_NON_ASCII) objectMapper.writerWithDefaultPrettyPrinter().with(JsonGenerator.Feature.ESCAPE_NON_ASCII)
@@ -289,14 +306,9 @@ class JacksonJsonApi : JsonApi {
} }
} }
override fun addJsonConverter(c: BaseJsonConverter<*, *>) { /**
try { * 将JSON字符串解析为JsonItem对象,解析失败时包装为JsonException抛出
objectMapper.registerModule(c.getJacksonModule()) */
} catch (e: Exception) {
throw JsonException("Failed to update node value", e)
}
}
override fun parseJsonItem(json: String): JsonItem { override fun parseJsonItem(json: String): JsonItem {
try { try {
return getJsonItem(objectMapper.readTree(json)) return getJsonItem(objectMapper.readTree(json))
@@ -306,8 +318,21 @@ class JacksonJsonApi : JsonApi {
} }
} }
/**
* 基于Jackson2的JsonItem标记实现类,通过伴生对象工厂方法创建具体的JsonItem
*/
class JackSonJsonItem : JsonItem { class JackSonJsonItem : JsonItem {
/**
* 伴生对象,提供JsonNode到JsonItem的工厂方法
*/
companion object { companion object {
/**
* 根据JsonNode的节点类型创建对应的JsonItem实例
*
* @param node Jackson2的JsonNode节点
* @return 与节点类型对应的JsonItem实例
* @throws IllegalStateException 当节点类型未知时抛出
*/
fun getJsonItem(node: JsonNode): JsonItem { fun getJsonItem(node: JsonNode): JsonItem {
return when (node.nodeType) { return when (node.nodeType) {
JsonNodeType.OBJECT -> JackSonJsonObject(node) JsonNodeType.OBJECT -> JackSonJsonObject(node)
@@ -322,11 +347,31 @@ class JackSonJsonItem : JsonItem {
} }
} }
/**
* 基于Jackson2节点的JSON数字类型
*
* @param node 数字类型的JsonNode节点
*/
class JackSonJsonNumber(node: JsonNode) : JsonNumber(node.asText()) class JackSonJsonNumber(node: JsonNode) : JsonNumber(node.asText())
/**
* 基于Jackson2节点的JSON布尔类型
*
* @param node 布尔类型的JsonNode节点
*/
class JackSonJsonBoolean(node: JsonNode) : JsonBoolean(node.asBoolean()) class JackSonJsonBoolean(node: JsonNode) : JsonBoolean(node.asBoolean())
/**
* 基于Jackson2节点的JSON字符串类型
*
* @param node 字符串类型的JsonNode节点
*/
class JackSonJsonString(node: JsonNode) : JsonString(node.asText()) class JackSonJsonString(node: JsonNode) : JsonString(node.asText())
/**
* 基于Jackson2节点的JSON数组类型
*
* @property node 数组类型的JsonNode节点
*/
class JackSonJsonArray(val node: JsonNode) : JsonArray() { class JackSonJsonArray(val node: JsonNode) : JsonArray() {
override fun getIndex(index: Int): JsonItem { override fun getIndex(index: Int): JsonItem {
return getJsonItem(node.get(index)) return getJsonItem(node.get(index))
@@ -348,6 +393,11 @@ class JackSonJsonArray(val node: JsonNode) : JsonArray() {
} }
} }
/**
* 基于Jackson2节点的JSON对象类型
*
* @property node 对象类型的JsonNode节点
*/
class JackSonJsonObject(val node: JsonNode) : JsonObject() { class JackSonJsonObject(val node: JsonNode) : JsonObject() {
override fun getField(name: String): JsonItem { override fun getField(name: String): JsonItem {
return getJsonItem(node.get(name)) return getJsonItem(node.get(name))
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JsonApi.kt * CurrentFile JsonApi.kt
* LastUpdate 2026-03-27 14:19:31 * LastUpdate 2026-11-17 19:59:21
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -25,8 +25,6 @@ package com.mingliqiye.utils.json.api.base
import com.mingliqiye.utils.exception.JsonParserException import com.mingliqiye.utils.exception.JsonParserException
import com.mingliqiye.utils.json.api.type.JsonTypeReference import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.api.type.listType import com.mingliqiye.utils.json.api.type.listType
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJsonConverter
import com.mingliqiye.utils.json.objects.base.JsonItem import com.mingliqiye.utils.json.objects.base.JsonItem
import okio.IOException import okio.IOException
import java.io.* import java.io.*
@@ -40,6 +38,9 @@ import kotlin.io.path.readBytes
*/ */
interface JsonApi { interface JsonApi {
/**
* 伴生对象,提供基于 reified 泛型参数的便捷解析与转换扩展函数
*/
companion object { companion object {
/** /**
* 将JSON字符串解析为指定泛型类型对象 * 将JSON字符串解析为指定泛型类型对象
@@ -131,17 +132,6 @@ interface JsonApi {
*/ */
@JvmStatic @JvmStatic
inline fun <reified D> JsonApi.convert(source: Any): D = convert(source, object : JsonTypeReference<D>() {}) inline fun <reified D> JsonApi.convert(source: Any): D = convert(source, object : JsonTypeReference<D>() {})
/**
* 添加JSON转换器到API中
*
* @param T 需要添加的JSON转换器类
*/
@JvmStatic
inline fun <reified T : BaseJsonConverter<*, *>> JsonApi.addJsonConverter() {
addJsonConverter(getJsonConverter<T>())
}
} }
/** /**
@@ -355,46 +345,106 @@ interface JsonApi {
*/ */
fun formatPretty(obj: Any): String fun formatPretty(obj: Any): String
/**
* 将对象格式化为美化格式的JSON字节数组
*
* @param obj 待格式化的对象
* @return 格式化后的美化JSON字节数组
*/
fun formatPrettyBytes(obj: Any): ByteArray { fun formatPrettyBytes(obj: Any): ByteArray {
return formatPretty(obj)!!.toByteArray() return formatPretty(obj)!!.toByteArray()
} }
/**
* 将对象格式化为美化JSON并写入指定路径的文件
*
* @param obj 待格式化的对象
* @param file 目标文件路径
*/
fun formatPretty(obj: Any, file: String) { fun formatPretty(obj: Any, file: String) {
formatPretty(obj, Paths.get(file)) formatPretty(obj, Paths.get(file))
} }
/**
* 将对象格式化为美化JSON并写入指定路径的文件
*
* @param obj 待格式化的对象
* @param file 目标文件路径对象
*/
fun formatPretty(obj: Any, file: Path) { fun formatPretty(obj: Any, file: Path) {
formatPretty(obj, file.toFile()) formatPretty(obj, file.toFile())
} }
/**
* 将对象格式化为美化JSON并写入指定文件
*
* @param obj 待格式化的对象
* @param file 目标文件对象
*/
fun formatPretty(obj: Any, file: File) { fun formatPretty(obj: Any, file: File) {
FileOutputStream(file).use { fos -> FileOutputStream(file).use { fos ->
formatPretty(obj, fos) formatPretty(obj, fos)
} }
} }
/**
* 将对象格式化为美化JSON并写入输出流
*
* @param obj 待格式化的对象
* @param stream 目标输出流
*/
fun formatPretty(obj: Any, stream: OutputStream) { fun formatPretty(obj: Any, stream: OutputStream) {
stream.write(formatPrettyBytes(obj)) stream.write(formatPrettyBytes(obj))
} }
/**
* 将对象格式化为JSON字节数组
*
* @param obj 待格式化的对象
* @return 格式化后的JSON字节数组
*/
fun formatBytes(obj: Any): ByteArray { fun formatBytes(obj: Any): ByteArray {
return format(obj).toByteArray() return format(obj).toByteArray()
} }
/**
* 将对象格式化为JSON并写入指定路径的文件
*
* @param obj 待格式化的对象
* @param file 目标文件路径
*/
fun format(obj: Any, file: String) { fun format(obj: Any, file: String) {
format(obj, Paths.get(file)) format(obj, Paths.get(file))
} }
/**
* 将对象格式化为JSON并写入指定路径的文件
*
* @param obj 待格式化的对象
* @param file 目标文件路径对象
*/
fun format(obj: Any, file: Path) { fun format(obj: Any, file: Path) {
format(obj, file.toFile()) format(obj, file.toFile())
} }
/**
* 将对象格式化为JSON并写入指定文件
*
* @param obj 待格式化的对象
* @param file 目标文件对象
*/
fun format(obj: Any, file: File) { fun format(obj: Any, file: File) {
FileOutputStream(file).use { fos -> FileOutputStream(file).use { fos ->
format(obj, fos) format(obj, fos)
} }
} }
/**
* 将对象格式化为JSON并写入输出流
*
* @param obj 待格式化的对象
* @param stream 目标输出流
*/
fun format(obj: Any, stream: OutputStream) { fun format(obj: Any, stream: OutputStream) {
stream.write(formatPrettyBytes(obj)) stream.write(formatPrettyBytes(obj))
} }
@@ -513,20 +563,6 @@ interface JsonApi {
*/ */
fun <D> convert(source: Any, destinationType: JsonTypeReference<D>): D fun <D> convert(source: Any, destinationType: JsonTypeReference<D>): D
/**
* 注册自定义的 JSON 转换器
* 用于处理特定类型的自定义序列化和反序列化逻辑
*
* @param c 自定义的 JSON 转换器实例
*
* 使用示例:
* ```
* converter.addJsonConverter(DateJsonConverter())
* converter.addJsonConverter(LocalDateTimeJsonConverter())
* ```
*/
fun addJsonConverter(c: BaseJsonConverter<*, *>)
/** /**
* 将 JSON 字符串解析为 JsonItem 对象 * 将 JSON 字符串解析为 JsonItem 对象
* *
@@ -34,6 +34,9 @@ import java.util.*
*/ */
abstract class JsonTypeReference<T> : Comparable<JsonTypeReference<T>> { abstract class JsonTypeReference<T> : Comparable<JsonTypeReference<T>> {
/**
* 当前引用的类型信息,子类可覆写以自定义类型
*/
open var type: Type = Any::class.java open var type: Type = Any::class.java
/** /**
@@ -68,6 +71,12 @@ abstract class JsonTypeReference<T> : Comparable<JsonTypeReference<T>> {
* @return 类型引用实例 * @return 类型引用实例
*/ */
companion object { companion object {
/**
* 根据 reified 泛型参数创建类型引用
*
* @param <T> 目标类型
* @return 类型引用实例
*/
inline fun <reified T> of(): JsonTypeReference<T> { inline fun <reified T> of(): JsonTypeReference<T> {
return object : JsonTypeReference<T>() {} return object : JsonTypeReference<T>() {}
} }
@@ -27,6 +27,12 @@ import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type import java.lang.reflect.Type
import java.lang.reflect.WildcardType import java.lang.reflect.WildcardType
/**
* 参数化类型的简单实现,用于在运行时构造并描述带泛型参数的类型
*
* @property rawClass 原始类型(如 List::class.java)
* @param paramType 泛型参数类型列表
*/
class TypeReference( class TypeReference(
val rawClass: Type, val rawClass: Type,
vararg paramType: Type, vararg paramType: Type,
@@ -40,12 +46,24 @@ class TypeReference(
override fun getOwnerType(): Type? = null override fun getOwnerType(): Type? = null
/**
* 返回"原始类型<参数1,参数2>"形式的类型描述字符串
*/
override fun toString(): String = "${getRawString(rawClass)}<${ override fun toString(): String = "${getRawString(rawClass)}<${
",".join(typeArguments) { getRawString(it) } ",".join(typeArguments) { getRawString(it) }
}>" }>"
/**
* 伴生对象,提供类型描述与TypeReference的工厂方法
*/
companion object { companion object {
/**
* 获取类型的完整描述字符串,支持通配符与参数化类型
*
* @param type 类型对象
* @return 类型的描述字符串
*/
fun getRawString(type: Type): String { fun getRawString(type: Type): String {
return when (type) { return when (type) {
is Class<*> -> type.name is Class<*> -> type.name
@@ -73,10 +91,23 @@ class TypeReference(
} }
} }
/**
* 根据 reified 泛型参数创建TypeReference
*
* @param <T> 目标类型
* @return TypeReference实例
*/
inline fun <reified T> of(): TypeReference { inline fun <reified T> of(): TypeReference {
return of((object : JsonTypeReference<T>() {}).type) return of((object : JsonTypeReference<T>() {}).type)
} }
/**
* 将任意Type转换为TypeReference
*
* @param type 类型对象,支持Class、ParameterizedType和WildcardType
* @return TypeReference实例
* @throws IllegalStateException 当类型无法识别时抛出
*/
fun of(type: Type): TypeReference { fun of(type: Type): TypeReference {
return when (type) { return when (type) {
is Class<*> -> TypeReference(type) is Class<*> -> TypeReference(type)
@@ -16,82 +16,65 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile DateTimeJsonConverter.kt * CurrentFile DateTimeJsonConverter.kt
* LastUpdate 2026-11-09 14:35:06 * LastUpdate 2026-11-17 20:17:32
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.json.converters package com.mingliqiye.utils.json.converters
import com.google.gson.JsonParseException
import com.mingliqiye.utils.annotation.DateTimeJsonFormat import com.mingliqiye.utils.annotation.DateTimeJsonFormat
import com.mingliqiye.utils.json.api.type.JsonTypeReference import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.AnnotationGetter import com.mingliqiye.utils.json.converters.base.AnnotationGetter
import com.mingliqiye.utils.json.converters.base.AnnotationGetter.Companion.get import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.BaseJsonStringConverter import com.mingliqiye.utils.json.converters.base.getAnnotation
import com.mingliqiye.utils.objects.isNull import com.mingliqiye.utils.json.reader.base.BaseJsonReader
import com.mingliqiye.utils.string.isNullish import com.mingliqiye.utils.json.witer.base.BaseJsonWriter
import com.mingliqiye.utils.time.DateTime import com.mingliqiye.utils.time.DateTime
import com.mingliqiye.utils.time.Formatter import com.mingliqiye.utils.time.Formatter
/** /**
* DateTimeJsonConverter 是一个用于处理 DateTime 类型与 JSON 字符串之间转换的类。 * [DateTime] 的 JSON 字符串转换器。
* 它继承自 BaseJsonStringConverter,提供了序列化(convert)和反序列化(deConvert)的功能。
*/
class DateTimeJsonConverter private constructor() : BaseJsonStringConverter<DateTime> {
companion object {
private val dateTimeJsonConverter by lazy {
DateTimeJsonConverter()
}
@JvmStatic
fun getJsonConverter(): DateTimeJsonConverter = dateTimeJsonConverter
}
/**
* 将 DateTime 对象转换为 JSON 字符串。
* *
* @param obj 需要转换的 DateTime 对象,可能为 null。 * 根据字段上的 [DateTimeJsonFormat] 注解选择格式化器,
* @param annotationGetter 用于获取注解信息的对象,用于决定格式化方式。 * 在日期时间对象与 JSON 字符串之间进行双向转换。
* @return 转换后的字符串,如果输入为 null 则返回 null。 */
* @throws Exception 如果在转换过程中发生异常。 class DateTimeJsonConverter : BaseJsonConverter<DateTime> {
/**
* 按 [DateTimeJsonFormat] 注解指定的格式将日期时间写为 JSON 字符串,null 时写入 null
*/ */
@Throws(Exception::class) @Throws(Exception::class)
override fun convert(obj: DateTime?, annotationGetter: AnnotationGetter): String? { override fun convert(
// 如果输入对象为 null,直接返回 null obj: DateTime?,
if (obj.isNull()) return null jsonWriter: BaseJsonWriter,
annotationGetter: AnnotationGetter,
// 获取 DateTimeJsonFormat 注解信息 ) {
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.get<DateTimeJsonFormat>() if (obj == null) {
jsonWriter.setNull()
// 根据注解中的格式化规则进行转换 return
return if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) { }
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.getAnnotation<DateTimeJsonFormat>()
val value = if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) {
obj.format(dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero) obj.format(dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero)
} else if (dateTimeJsonFormat?.formatter?.isEmpty() == false) { } else if (dateTimeJsonFormat?.formatter?.isEmpty() == false) {
obj.format(dateTimeJsonFormat.formatter, dateTimeJsonFormat.repcZero) obj.format(dateTimeJsonFormat.formatter, dateTimeJsonFormat.repcZero)
} else { } else {
obj.format() obj.format()
} }
jsonWriter.setString(value)
} }
/** /**
* 将 JSON 字符串转换为 DateTime 对象。 * 按 [DateTimeJsonFormat] 注解指定的格式从 JSON 字符串解析日期时间
* *
* @param obj 需要转换的字符串,可能为 null 或空。 * @throws JsonParseException 当节点不是字符串类型时抛出
* @param annotationGetter 用于获取注解信息的对象,用于决定解析方式。
* @return 解析后的 DateTime 对象,如果输入为 null 或空则返回 null。
* @throws Exception 如果在解析过程中发生异常。
*/ */
@Throws(Exception::class) override fun deConvert(jsonReader: BaseJsonReader, annotationGetter: AnnotationGetter): DateTime? {
override fun deConvert(obj: String?, annotationGetter: AnnotationGetter): DateTime? { val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.getAnnotation<DateTimeJsonFormat>()
// 如果输入字符串为 null 或空,直接返回 null if (jsonReader.isNull) return null
if (obj.isNullish()) return null if (!jsonReader.isString) throw JsonParseException("type item not string")
val obj = jsonReader.getString()
// 获取 DateTimeJsonFormat 注解信息
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.get<DateTimeJsonFormat>()
// 根据注解中的解析规则进行转换
return if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) { return if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) {
DateTime.parse(obj, dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero) DateTime.parse(obj, dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero)
} else if (dateTimeJsonFormat?.formatter?.isEmpty() == false) { } else if (dateTimeJsonFormat?.formatter?.isEmpty() == false) {
@@ -101,12 +84,5 @@ class DateTimeJsonConverter private constructor() : BaseJsonStringConverter<Date
} }
} }
/** override fun getType(): JsonTypeReference<DateTime> = JsonTypeReference.of<DateTime>()
* 获取当前转换器支持的目标类型引用。
*
* @return 返回 DateTime 类型的 JsonTypeReference。
* @throws Exception 如果在获取类型引用时发生异常。
*/
@Throws(Exception::class)
override fun getFromType(): JsonTypeReference<DateTime> = JsonTypeReference.of<DateTime>()
} }
@@ -16,16 +16,18 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile NetworkEndpointJsonConverter.kt * CurrentFile NetworkEndpointJsonConverter.kt
* LastUpdate 2026-11-09 14:36:36 * LastUpdate 2026-11-17 20:01:08
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.json.converters package com.mingliqiye.utils.json.converters
import com.google.gson.JsonParseException
import com.mingliqiye.utils.json.api.type.JsonTypeReference import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.NetworkEndpointJsonConverter.Companion.getJsonConverter
import com.mingliqiye.utils.json.converters.base.AnnotationGetter import com.mingliqiye.utils.json.converters.base.AnnotationGetter
import com.mingliqiye.utils.json.converters.base.BaseJsonStringConverter import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.reader.base.BaseJsonReader
import com.mingliqiye.utils.json.witer.base.BaseJsonWriter
import com.mingliqiye.utils.network.NetworkEndpoint import com.mingliqiye.utils.network.NetworkEndpoint
/** /**
@@ -41,60 +43,32 @@ import com.mingliqiye.utils.network.NetworkEndpoint
* @see BaseJsonStringConverter * @see BaseJsonStringConverter
* @see NetworkEndpoint * @see NetworkEndpoint
*/ */
class NetworkEndpointJsonConverter private constructor() : BaseJsonStringConverter<NetworkEndpoint> { class NetworkEndpointJsonConverter : BaseJsonConverter<NetworkEndpoint> {
/**
companion object { * 将网络端点写为 `host:port` 形式的 JSON 字符串,null 时写入 null
private val networkEndpointJsonConverter by lazy { */
NetworkEndpointJsonConverter() override fun convert(
obj: NetworkEndpoint?,
jsonWriter: BaseJsonWriter,
annotationGetter: AnnotationGetter,
) {
if (obj == null) jsonWriter.setNull() else jsonWriter.setString(obj.toHostPortString())
} }
/** /**
* 获取 [NetworkEndpointJsonConverter] 的全局单例。 * 从 `host:port` 形式的 JSON 字符串还原网络端点
* *
* @return 共享的转换器实例。 * @throws JsonParseException 当节点不是字符串类型时抛出
*/ */
@JvmStatic override fun deConvert(
fun getJsonConverter(): NetworkEndpointJsonConverter = networkEndpointJsonConverter jsonReader: BaseJsonReader,
annotationGetter: AnnotationGetter,
): NetworkEndpoint? {
return if (jsonReader.isNotNull) {
if (!jsonReader.isString) throw JsonParseException("type item not string")
NetworkEndpoint.of(jsonReader.getString())
} else null
} }
/** override fun getType(): JsonTypeReference<NetworkEndpoint> = JsonTypeReference.of()
* 将 [NetworkEndpoint] 序列化为 JSON 字符串。
*
* 输出格式为 `host:port`,由 [NetworkEndpoint.toHostPortString] 生成。
*
* @param obj 待序列化的网络端点,可能为 `null`。
* @param annotationGetter 注解信息提供者,用于在需要时读取格式化相关注解;
* 当前实现不依赖注解,保留该参数以符合转换器契约。
* @return 序列化后的 `host:port` 字符串;当 [obj] 为 `null` 时返回 `null`。
* @throws Exception 若序列化过程中发生异常。
*/
@Throws(Exception::class)
override fun convert(obj: NetworkEndpoint?, annotationGetter: AnnotationGetter): String? {
return obj?.let(NetworkEndpoint::toHostPortString)
}
/**
* 将 JSON 字符串反序列化为 [NetworkEndpoint]。
*
* 期望输入为 `host:port` 形式的字符串,由 [NetworkEndpoint.Companion.of] 解析。
*
* @param obj 待反序列化的字符串,可能为 `null`。
* @param annotationGetter 注解信息提供者,用于在需要时读取解析相关注解;
* 当前实现不依赖注解,保留该参数以符合转换器契约。
* @return 解析得到的 [NetworkEndpoint];当 [obj] 为 `null` 时返回 `null`。
* @throws Exception 若字符串格式非法或解析过程中发生异常。
*/
@Throws(Exception::class)
override fun deConvert(obj: String?, annotationGetter: AnnotationGetter): NetworkEndpoint? {
return obj?.let(NetworkEndpoint.Companion::of)
}
/**
* 获取本转换器支持的目标类型引用。
*
* @return 指向 [NetworkEndpoint] 的 [JsonTypeReference]。
* @throws Exception 若获取类型引用时发生异常。
*/
@Throws(Exception::class)
override fun getFromType(): JsonTypeReference<NetworkEndpoint> = JsonTypeReference.Companion.of()
} }
@@ -16,84 +16,74 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile UUIDJsonConverter.kt * CurrentFile UUIDJsonConverter.kt
* LastUpdate 2026-02-08 01:37:00 * LastUpdate 2026-11-17 20:01:08
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.json.converters package com.mingliqiye.utils.json.converters
import com.google.gson.JsonParseException
import com.mingliqiye.utils.annotation.UUIDJsonFormat import com.mingliqiye.utils.annotation.UUIDJsonFormat
import com.mingliqiye.utils.base.BaseType import com.mingliqiye.utils.base.BaseType
import com.mingliqiye.utils.json.api.type.JsonTypeReference import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.AnnotationGetter import com.mingliqiye.utils.json.converters.base.AnnotationGetter
import com.mingliqiye.utils.json.converters.base.AnnotationGetter.Companion.get import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.BaseJsonStringConverter import com.mingliqiye.utils.json.converters.base.getAnnotation
import com.mingliqiye.utils.objects.isNull import com.mingliqiye.utils.json.reader.base.BaseJsonReader
import com.mingliqiye.utils.string.isNullish import com.mingliqiye.utils.json.witer.base.BaseJsonWriter
import com.mingliqiye.utils.uuid.UUID import com.mingliqiye.utils.uuid.UUID
import com.mingliqiye.utils.uuid.UUIDFormatType import com.mingliqiye.utils.uuid.UUIDFormatType
/** /**
* UUIDJsonConverter 是一个用于处理 UUID 类型与 JSON 字符串之间转换的类。 * [UUID] 的 JSON 字符串转换器。
* 它继承自 BaseJsonStringConverter,并实现了 convert 和 deConvert 方法, *
* 分别用于将 UUID 对象序列化为字符串以及反序列化字符串为 UUID 对象。 * 根据字段上的 [UUIDJsonFormat] 注解选择进制与格式,
* 在 UUID 对象与 JSON 字符串之间进行双向转换。
*/ */
class UUIDJsonConverter private constructor() : BaseJsonStringConverter<UUID> { class UUIDJsonConverter : BaseJsonConverter<UUID> {
companion object {
private val uuidJsonConverter by lazy {
UUIDJsonConverter()
}
@JvmStatic
fun getJsonConverter(): UUIDJsonConverter = uuidJsonConverter
}
/** /**
* 将 UUID 对象转换为字符串形式。 * 按 [UUIDJsonFormat] 注解指定的进制与格式将 UUID 写为 JSON 字符串,null 时写入 null
*
* @param obj 需要转换的 UUID 对象,可能为 null。
* @param annotationGetter 用于获取注解信息的对象。
* @return 转换后的字符串,如果输入为 null 则返回 null。
*/ */
override fun convert( override fun convert(
obj: UUID?, obj: UUID?,
jsonWriter: BaseJsonWriter,
annotationGetter: AnnotationGetter, annotationGetter: AnnotationGetter,
): String? { ) {
// 如果输入对象为 null,直接返回 null if (obj == null) {
if (obj.isNull()) return null jsonWriter.setNull()
return
}
val dateTimeJsonFormat: UUIDJsonFormat? = annotationGetter.getAnnotation<UUIDJsonFormat>()
// 获取 UUIDJsonFormat 注解信息,若未找到则使用默认格式
val dateTimeJsonFormat: UUIDJsonFormat = annotationGetter.get<UUIDJsonFormat>() ?: return obj.getString()
// 根据注解中的 base 和 value 属性选择合适的字符串表示方式 val uuid =
return if (BaseType.BASE16 != dateTimeJsonFormat.base) { if (dateTimeJsonFormat == null) obj.getString() else if (BaseType.BASE16 != dateTimeJsonFormat.base) {
obj.getString(dateTimeJsonFormat.base) obj.getString(dateTimeJsonFormat.base)
} else if (UUIDFormatType.NO_UPPER_SPACE != dateTimeJsonFormat.value) { } else if (UUIDFormatType.NO_UPPER_SPACE != dateTimeJsonFormat.value) {
obj.getString(dateTimeJsonFormat.value) obj.getString(dateTimeJsonFormat.value)
} else { } else {
obj.getString() obj.getString()
} }
jsonWriter.setString(uuid)
} }
/** /**
* 将字符串反序列化为 UUID 对象。 * 按 [UUIDJsonFormat] 注解指定的进制从 JSON 字符串解析 UUID
* *
* @param obj 需要反序列化的字符串,可能为 null 或空。 * @throws JsonParseException 当节点不是字符串类型时抛出
* @param annotationGetter 用于获取注解信息的对象。
* @return 反序列化后的 UUID 对象,如果输入无效则返回 null。
*/ */
override fun deConvert( override fun deConvert(
obj: String?, jsonReader: BaseJsonReader,
annotationGetter: AnnotationGetter, annotationGetter: AnnotationGetter,
): UUID? { ): UUID? {
// 如果输入字符串为 null 或空,直接返回 null if (jsonReader.isNull) return null
if (obj.isNullish()) return null if (!jsonReader.isString) throw JsonParseException("type item not string")
// 获取 UUIDJsonFormat 注解信息,若未找到则使用默认解析方式 val obj = jsonReader.getString()
val dateTimeJsonFormat: UUIDJsonFormat = annotationGetter.get<UUIDJsonFormat>() ?: return UUID.of(obj)
// 根据注解中的 base 属性选择合适的解析方式 val dateTimeJsonFormat: UUIDJsonFormat = annotationGetter.getAnnotation<UUIDJsonFormat>() ?: return UUID.of(obj)
return if (BaseType.BASE16 != dateTimeJsonFormat.base) { return if (BaseType.BASE16 != dateTimeJsonFormat.base) {
UUID.of(obj, dateTimeJsonFormat.base) UUID.of(obj, dateTimeJsonFormat.base)
} else { } else {
@@ -101,10 +91,5 @@ class UUIDJsonConverter private constructor() : BaseJsonStringConverter<UUID> {
} }
} }
/** override fun getType(): JsonTypeReference<UUID> = JsonTypeReference.of()
* 返回当前转换器支持的目标类型引用。
*
* @return 表示 UUID 类型的 JsonTypeReference 对象。
*/
override fun getFromType() = JsonTypeReference.of<UUID>()
} }
@@ -16,67 +16,21 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile AnnotationGetter.kt * CurrentFile AnnotationGetter.kt
* LastUpdate 2026-03-11 08:46:40 * LastUpdate 2026-11-17 19:46:16
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.json.converters.base package com.mingliqiye.utils.json.converters.base
/** /**
* 定义一个用于获取注解的接口。 * 注解获取接口,用于在自定义序列化/反序列化时读取字段上的注解
* 提供了一个通用方法来根据注解类型获取对应的注解实例。
*/ */
interface AnnotationGetter { interface AnnotationGetter {
/** /**
* 根据指定的注解类型获取该类型的注解实例。 * 获取指定类型的注解
* *
* @param clazz 注解的Class对象,表示要获取的注解类型。 * @param clazz 注解的Class类型
* @return 返回对应类型的注解实例,如果未找到则返回null。 * @return 注解实例,不存在时返回null(默认实现始终返回null)
*/ */
fun <T : Annotation> get(clazz: Class<T>): T? fun <T : Annotation> getAnnotation(clazz: Class<T>): T? = null
companion object {
/**
* 使用内联函数和重ified类型参数简化注解获取操作。
* 通过传入泛型参数自动推断注解类型,避免手动传递Class对象。
*
* @param T 注解类型,必须继承自Annotation。
* @return 返回对应类型的注解实例,如果未找到则返回null。
*/
inline fun <reified T : Annotation> AnnotationGetter.get(): T? = this.get(T::class.java)
/**
* 提供一个默认实现,始终返回null。
* 可用于需要空注解获取器的场景。
*/
val nullGetter = object : AnnotationGetter {
/**
* 始终返回null,不执行任何实际逻辑。
*
* @param clazz 注解的Class对象(未使用)。
* @return 始终返回null。
*/
override fun <T : Annotation> get(clazz: Class<T>): T? = null
}
/**
* 创建一个AnnotationGetter对象,用于根据指定的注解类型获取对应的注解实例。
*
* @param annotation 要包装的注解实例,作为内部逻辑的来源。
* @return 返回一个实现了AnnotationGetter接口的匿名对象。
*/
fun oneGetter(annotation: Annotation) = object : AnnotationGetter {
/**
* 根据传入的注解类型clazz,尝试返回与annotation匹配的注解实例。
*
* @param clazz 目标注解类型的Class对象。
* @return 如果annotation的类型与clazz一致,则返回annotation转换为T类型的实例;否则返回null。
*/
@Suppress("UNCHECKED_CAST")
override fun <T : Annotation> get(clazz: Class<T>): T? =
if (annotation.javaClass == clazz) annotation as T else null
}
}
} }
@@ -1,49 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonBigDecimalConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import java.math.BigDecimal
/**
* 接口 [BaseJsonBigDecimalConverter] 定义了一个用于将 JSON 数据转换为 [BigDecimal] 类型的转换器。
*
* 此接口继承自 [BaseJsonConverter],并指定目标类型为 [BigDecimal]。
* 实现此接口的类需要提供具体的转换逻辑。
*
* @param E 转换器处理的源数据类型。
*/
interface BaseJsonBigDecimalConverter<E> : BaseJsonConverter<E, BigDecimal> {
/**
* 获取目标类型的引用信息。
*
* 该方法返回一个 [JsonTypeReference] 对象,表示目标类型为 [BigDecimal]。
* 通过调用 [JsonTypeReference.Companion.of] 方法创建类型引用。
*
* @return 目标类型 [BigDecimal] 的类型引用。
* @throws Exception 如果在获取类型引用时发生异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<BigDecimal>()
}
@@ -1,45 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonBigIntegerConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import java.math.BigInteger
/**
* 接口 [BaseJsonBigIntegerConverter] 定义了一个用于将 JSON 数据转换为 `BigInteger` 类型的转换器。
* 该接口继承自 [BaseJsonConverter],并指定了泛型参数 [E] 和 `BigInteger`。
*
* @param E 表示需要转换的目标类型,由实现类具体指定。
*/
interface BaseJsonBigIntegerConverter<E> : BaseJsonConverter<E, BigInteger> {
/**
* 获取目标类型的引用,用于 JSON 反序列化时确定目标类型。
* 该方法重写了父接口中的 [getToType] 方法,并返回 `BigInteger` 类型的引用。
*
* @return 返回 [JsonTypeReference] 对象,表示 `BigInteger` 类型的引用。
* @throws Exception 如果在获取类型引用过程中发生异常,则抛出该异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<BigInteger>()
}
@@ -1,46 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonBooleanConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonBooleanConverter] 定义了一个用于处理布尔类型 JSON 转换的基础转换器。
*
* 该接口继承自 [BaseJsonConverter],并专门用于将某种类型 [E] 转换为布尔类型 [Boolean]。
* 实现该接口的类需要提供具体的转换逻辑。
*/
interface BaseJsonBooleanConverter<E> : BaseJsonConverter<E, Boolean> {
/**
* 获取目标类型的引用信息。
*
* 该方法返回一个 [JsonTypeReference] 对象,表示目标类型为 [Boolean]。
* 此方法重写了父接口中的定义,并通过 [JsonTypeReference.Companion.of] 方法获取布尔类型的引用。
*
* @return [JsonTypeReference<Boolean>] 表示布尔类型的引用。
* @throws Exception 如果在获取类型引用时发生异常,则抛出此异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Boolean>()
}
@@ -1,43 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonByteConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* BaseJsonByteConverter 是一个接口,继承自 BaseJsonConverter,用于定义字节类型(Byte)的 JSON 转换器。
*
* 该接口的主要作用是提供一个标准的字节类型转换实现,并通过 getToType 方法返回目标类型的引用。
*
* @param E 泛型参数,表示需要转换的目标对象类型。
*/
interface BaseJsonByteConverter<E> : BaseJsonConverter<E, Byte> {
/**
* 获取目标类型的引用,用于标识转换的目标类型为 Byte。
*
* @return 返回 JsonTypeReference 类型的实例,表示目标类型为 Byte。
* @throws Exception 如果在获取类型引用过程中发生异常,则抛出该异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Byte>()
}
@@ -16,19 +16,60 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile BaseJsonConverter.kt * CurrentFile BaseJsonConverter.kt
* LastUpdate 2026-02-26 15:59:35 * LastUpdate 2026-11-17 20:10:50
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.json.converters.base package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.reader.base.BaseJsonReader
import com.mingliqiye.utils.json.witer.base.BaseJsonWriter
/** /**
* BaseJsonConverter 是一个泛型接口,用于定义 JSON 转换器的基本行为。 * BaseJsonConverter 是一个通用的 JSON 转换器接口,用于定义对象之间的双向转换逻辑。
* *
* 该接口继承自 JackSonJsonConverter,并通过泛型参数 F 和 T 定义了转换的源类型和目标类型。 * @param F 源类型,表示需要被转换的对象类型。
* 实现该接口的类需要提供具体的 JSON 转换逻辑。 * @param T 目标类型,表示转换后的对象类型。
*
* @param F 源类型,表示需要被转换的数据类型。
* @param T 目标类型,表示转换后的数据类型。
*/ */
interface BaseJsonConverter<F, T> : JsonConverter<F, T> interface BaseJsonConverter<T> {
/**
* 序列化:将对象转换并写入 JSON
*
* @param obj 待写入的对象,可能为null
* @param jsonWriter JSON写入器
* @param annotationGetter 注解获取器,用于读取字段上的格式注解
* @throws Exception 当写入失败时抛出
*/
@Throws(Exception::class)
fun convert(obj: T?, jsonWriter: BaseJsonWriter, annotationGetter: AnnotationGetter)
/**
* 反序列化:从 JSON 读取并还原对象
*
* @param jsonReader JSON读取器
* @param annotationGetter 注解获取器,用于读取字段上的格式注解
* @return 还原后的对象,JSON为null时返回null
* @throws Exception 当读取失败时抛出
*/
@Throws(Exception::class)
fun deConvert(jsonReader: BaseJsonReader, annotationGetter: AnnotationGetter): T?
/**
* 获取本转换器处理的目标类型引用
*
* @return 目标类型的JsonTypeReference
* @throws Exception 当获取类型失败时抛出
*/
@Throws(Exception::class)
fun getType(): JsonTypeReference<T>
/**
* 获取本转换器处理的目标类型的原始Class
*
* @return 目标类型的Class对象
*/
@Throws(Exception::class)
fun getClazz() = getType().getRawType()
}
@@ -1,42 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonDoubleConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* BaseJsonDoubleConverter 是一个接口,继承自 BaseJsonConverter,
* 用于定义将 JSON 数据转换为 Double 类型的转换器。
*
* @param E 泛型参数,表示需要转换的目标类型。
*/
interface BaseJsonDoubleConverter<E> : BaseJsonConverter<E, Double> {
/**
* 获取目标类型的引用,用于标识转换的目标类型为 Double。
*
* @return 返回 JsonTypeReference<Double> 类型的实例,表示目标类型为 Double。
* @throws Exception 如果在获取类型引用时发生异常,则抛出该异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Double>()
}
@@ -1,46 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonFloatConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonFloatConverter] 定义了一个用于处理浮点数类型 JSON 转换的基础转换器。
*
* 该接口继承自 [BaseJsonConverter],并指定泛型参数 [E] 和 [Float],
* 表示将某种类型 [E] 转换为 [Float] 类型的 JSON 数据。
*/
interface BaseJsonFloatConverter<E> : BaseJsonConverter<E, Float> {
/**
* 获取目标类型的引用信息。
*
* 该方法重写了父接口中的 [getToType] 方法,返回 [Float] 类型的 [JsonTypeReference] 实例。
* 用于标识当前转换器的目标类型为 [Float]。
*
* @return [JsonTypeReference] 表示 [Float] 类型的引用信息。
* @throws Exception 如果在获取类型引用时发生异常,则抛出此异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Float>()
}
@@ -1,46 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonIntConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonIntConverter] 是一个泛型接口,继承自 [BaseJsonConverter],
* 用于定义将 JSON 数据转换为 [Int] 类型的转换器。
*
* @param E 表示需要转换的目标类型,通常是一个具体的业务实体或数据模型。
*/
interface BaseJsonIntConverter<E> : BaseJsonConverter<E, Int> {
/**
* 获取目标类型的引用信息。
*
* 该方法重写了父接口中的 [getToType] 方法,返回 [Int] 类型的 [JsonTypeReference] 实例。
* 用于标识当前转换器的目标类型为 [Int]。
*
* @return 返回 [JsonTypeReference] 的实例,表示目标类型为 [Int]。
* @throws Exception 如果在获取类型引用时发生异常,则抛出该异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Int>()
}
@@ -1,43 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonLongConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonLongConverter] 定义了一个用于将 JSON 数据转换为 Long 类型的转换器。
*
* 此接口继承自 [BaseJsonConverter],并指定泛型参数 [E] 和 [Long],
* 表示该转换器处理的是从类型 [E] 到 [Long] 的转换。
*/
interface BaseJsonLongConverter<E> : BaseJsonConverter<E, Long> {
/**
* 获取目标类型的引用,用于标识此转换器的目标类型为 [Long]。
*
* @return 返回 [JsonTypeReference] 的实例,表示目标类型为 [Long]。
* @throws Exception 如果在获取类型引用时发生异常,则抛出此异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Long>()
}
@@ -1,46 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonShortConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonShortConverter] 定义了一个用于将 JSON 数据转换为 Short 类型的转换器。
*
* 该接口继承自 [BaseJsonConverter],并指定泛型参数 [E] 和 [Short],
* 表示该转换器处理的源类型为 [E],目标类型为 [Short]。
*/
interface BaseJsonShortConverter<E> : BaseJsonConverter<E, Short> {
/**
* 获取目标类型的引用信息。
*
* 该方法重写了父接口中的 [getToType] 方法,返回 [Short] 类型的 [JsonTypeReference] 实例。
* 通过 [JsonTypeReference.Companion.of] 方法创建类型引用。
*
* @return [JsonTypeReference] 表示 [Short] 类型的引用。
* @throws Exception 如果在获取类型引用过程中发生异常,则抛出该异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Short>()
}
@@ -1,46 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonStringConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonStringConverter] 定义了一个用于 JSON 字符串转换的基础接口。
*
* 该接口继承自 [BaseJsonConverter],并指定泛型参数 [E] 和 [String],
* 表示将类型 [E] 转换为字符串类型的 JSON 数据。
*/
interface BaseJsonStringConverter<E> : BaseJsonConverter<E, String> {
/**
* 获取目标类型的引用信息。
*
* 该方法重写了父接口中的 [getToType] 方法,返回一个表示 [String] 类型的 [JsonTypeReference] 实例。
* 此方法可能抛出异常,因此使用 [@Throws(Exception::class)] 注解标记。
*
* @return 返回一个 [JsonTypeReference] 实例,表示目标类型为 [String]。
* @throws Exception 如果在获取类型引用时发生错误,则抛出此异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<String>()
}
@@ -16,32 +16,50 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JackJson3Deserializer.kt * CurrentFile JackJson3Deserializer.kt
* LastUpdate 2026-02-26 13:02:52 * LastUpdate 2026-11-17 19:51:20
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.json.converters.base package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.reader.JackSon3JsonReader
import tools.jackson.core.JsonParser import tools.jackson.core.JsonParser
import tools.jackson.core.JsonToken
import tools.jackson.databind.BeanProperty import tools.jackson.databind.BeanProperty
import tools.jackson.databind.DeserializationContext import tools.jackson.databind.DeserializationContext
import tools.jackson.databind.ValueDeserializer import tools.jackson.databind.ValueDeserializer
class JackJson3Deserializer<F, T>( /**
* Jackson3 反序列化适配器,将 [BaseJsonConverter] 包装为 Jackson3 的 [ValueDeserializer]。
*
* @property property 当前属性信息,用于读取字段注解,可为null
* @property jsonConverter 实际执行反序列化逻辑的转换器
*/
class JackJson3Deserializer<T>(
val property: BeanProperty? = null, val property: BeanProperty? = null,
val jsonConverter: JsonConverter<F, T>, val jsonConverter: BaseJsonConverter<T>,
) : ValueDeserializer<F>() { ) : ValueDeserializer<T>() {
/**
* 注解获取器,从当前属性信息中读取字段注解
*/
val annotationGetter =
object : AnnotationGetter {
override fun <T : Annotation> getAnnotation(clazz: Class<T>): T? = property?.getAnnotation(clazz)
}
/**
* 反序列化方法:将 JSON 树交给转换器还原为目标对象。
*
* @param p JSON 解析器。
* @param ctxt 反序列化上下文,可选参数。
* @return 还原后的对象,可能为null。
*/
override fun deserialize( override fun deserialize(
p: JsonParser, p: JsonParser,
ctxt: DeserializationContext?, ctxt: DeserializationContext?,
): F? { ): T? {
if (p.currentToken() == JsonToken.VALUE_NULL) return null return jsonConverter.deConvert(JackSon3JsonReader(p.readValueAsTree()), annotationGetter)
return jsonConverter.deConvert(p.readValueAs(jsonConverter.getToClass()), object : AnnotationGetter {
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
})
} }
/** /**
@@ -54,7 +72,7 @@ class JackJson3Deserializer<F, T>(
override fun createContextual( override fun createContextual(
ctxt: DeserializationContext?, ctxt: DeserializationContext?,
property: BeanProperty?, property: BeanProperty?,
): JackJson3Deserializer<F, T> { ): JackJson3Deserializer<T> {
return JackJson3Deserializer(property, jsonConverter) return JackJson3Deserializer(property, jsonConverter)
} }
@@ -16,50 +16,56 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JackJson3Serializer.kt * CurrentFile JackJson3Serializer.kt
* LastUpdate 2026-02-26 13:04:18 * LastUpdate 2026-11-17 19:51:33
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.json.converters.base package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.witer.JackSon3JsonWriter
import tools.jackson.core.JsonGenerator
import tools.jackson.databind.BeanProperty import tools.jackson.databind.BeanProperty
import tools.jackson.databind.SerializationContext import tools.jackson.databind.SerializationContext
import tools.jackson.databind.ValueSerializer import tools.jackson.databind.ValueSerializer
import java.math.BigDecimal
import java.math.BigInteger
class JackJson3Serializer<F, T>(
val property: BeanProperty? = null,
val jsonConverter: JsonConverter<F, T>,
) : ValueSerializer<F>() {
/** /**
* 序列化方法:将源对象转换为目标对象,并根据目标对象的类型写入 JSON。 * Jackson3 序列化适配器,将 [BaseJsonConverter] 包装为 Jackson3 的 [ValueSerializer]。
* *
* @param value 源对象,可能为 null。 * @property property 当前属性信息,用于读取字段注解,可为null
* @param gen JSON 生成器,用于写入 JSON 数据。 * @property jsonConverter 实际执行序列化逻辑的转换器
* @param provider 序列化提供者,可选参数。
*/ */
override fun serialize(value: F, gen: tools.jackson.core.JsonGenerator, ctxt: SerializationContext) { class JackJson3Serializer<T>(
val data: T? = jsonConverter.convert(value, object : AnnotationGetter { val property: BeanProperty? = null,
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz) val jsonConverter: BaseJsonConverter<T>,
}) ) : ValueSerializer<T>() {
when (data) {
null -> gen.writeNull() /**
is String -> gen.writeString(data) * 注解获取器,从当前属性信息中读取字段注解
is Long -> gen.writeNumber(data) */
is Short -> gen.writeNumber(data) val annotationGetter =
is Byte -> gen.writeNumber(data.toShort()) object : AnnotationGetter {
is Int -> gen.writeNumber(data) override fun <T : Annotation> getAnnotation(clazz: Class<T>): T? = property?.getAnnotation(clazz)
is BigDecimal -> gen.writeNumber(data)
is BigInteger -> gen.writeNumber(data)
is Float -> gen.writeNumber(data)
is Double -> gen.writeNumber(data)
is Boolean -> gen.writeBoolean(data)
else -> throw IllegalArgumentException("not sport data type ${data.javaClass} $data")
}
} }
/**
* 序列化方法:将源对象交给转换器写入 JSON。
*
* @param value 源对象。
* @param gen JSON 生成器,用于写入 JSON 数据。
* @param ctxt 序列化上下文。
*/
override fun serialize(value: T, gen: JsonGenerator, ctxt: SerializationContext) {
jsonConverter.convert(value, JackSon3JsonWriter(gen, ctxt), annotationGetter)
}
/**
* 上下文感知方法:设置当前属性信息。
*
* @param ctxt 序列化上下文,可选参数。
* @param property 当前属性信息。
* @return 携带属性信息的新序列化器实例。
*/
override fun createContextual(ctxt: SerializationContext?, property: BeanProperty?): ValueSerializer<*> { override fun createContextual(ctxt: SerializationContext?, property: BeanProperty?): ValueSerializer<*> {
return JackJson3Serializer(property, jsonConverter) return JackJson3Serializer(property, jsonConverter)
} }
@@ -16,31 +16,51 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JackJsonDeserializer.kt * CurrentFile JackJsonDeserializer.kt
* LastUpdate 2026-02-08 02:22:46 * LastUpdate 2026-11-17 19:53:29
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.json.converters.base package com.mingliqiye.utils.json.converters.base
import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.databind.BeanProperty import com.fasterxml.jackson.databind.BeanProperty
import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.deser.ContextualDeserializer import com.fasterxml.jackson.databind.deser.ContextualDeserializer
import com.mingliqiye.utils.json.reader.JackSonJsonReader
class JackJsonDeserializer<F, T>( /**
* Jackson2 反序列化适配器,将 [BaseJsonConverter] 包装为 Jackson2 的 [JsonDeserializer]。
*
* @property property 当前属性信息,用于读取字段注解,可为null
* @property jsonConverter 实际执行反序列化逻辑的转换器
*/
class JackJsonDeserializer<T>(
val property: BeanProperty? = null, val property: BeanProperty? = null,
val jsonConverter: JsonConverter<F, T>, val jsonConverter: BaseJsonConverter<T>,
) : JsonDeserializer<F>(), ContextualDeserializer { ) : JsonDeserializer<T>(), ContextualDeserializer {
/**
* 注解获取器,从当前属性信息中读取字段注解
*/
val annotationGetter =
object : AnnotationGetter {
override fun <T : Annotation> getAnnotation(clazz: Class<T>): T? = property?.getAnnotation(clazz)
}
/**
* 反序列化方法:将 JSON 树交给转换器还原为目标对象。
*
* @param p JSON 解析器。
* @param ctxt 反序列化上下文,可选参数。
* @return 还原后的对象,可能为null。
*/
override fun deserialize( override fun deserialize(
p: JsonParser, p: JsonParser,
ctxt: DeserializationContext?, ctxt: DeserializationContext?,
): F? { ): T? {
if (p.currentToken == JsonToken.VALUE_NULL) return null return jsonConverter.deConvert(JackSonJsonReader(p.readValueAsTree()), annotationGetter)
return jsonConverter.deConvert(p.readValueAs(jsonConverter.getToClass()), object : AnnotationGetter {
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
})
} }
/** /**
@@ -48,12 +68,12 @@ class JackJsonDeserializer<F, T>(
* *
* @param ctxt 反序列化上下文,可选参数。 * @param ctxt 反序列化上下文,可选参数。
* @param property 当前属性信息。 * @param property 当前属性信息。
* @return 返回当前反序列化器实例。 * @return 携带属性信息的新反序列化器实例。
*/ */
override fun createContextual( override fun createContextual(
ctxt: DeserializationContext?, ctxt: DeserializationContext?,
property: BeanProperty?, property: BeanProperty?,
): JackJsonDeserializer<F, T> { ): JackJsonDeserializer<T> {
return JackJsonDeserializer(property, jsonConverter) return JackJsonDeserializer(property, jsonConverter)
} }
} }
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JackJsonSerializer.kt * CurrentFile JackJsonSerializer.kt
* LastUpdate 2026-02-26 12:55:57 * LastUpdate 2026-11-17 19:54:12
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -27,13 +27,25 @@ import com.fasterxml.jackson.databind.BeanProperty
import com.fasterxml.jackson.databind.JsonSerializer import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.ser.ContextualSerializer import com.fasterxml.jackson.databind.ser.ContextualSerializer
import java.math.BigDecimal import com.mingliqiye.utils.json.witer.JackSonJsonWriter
import java.math.BigInteger
class JackJsonSerializer<F, T>( /**
* Jackson2 序列化适配器,将 [BaseJsonConverter] 包装为 Jackson2 的 [JsonSerializer]。
*
* @property property 当前属性信息,用于读取字段注解,可为null
* @property jsonConverter 实际执行序列化逻辑的转换器
*/
class JackJsonSerializer<T>(
val property: BeanProperty?, val property: BeanProperty?,
val jsonConverter: JsonConverter<F, T>, val jsonConverter: BaseJsonConverter<T>,
) : JsonSerializer<F>(), ContextualSerializer { ) : JsonSerializer<T>(), ContextualSerializer {
/**
* 注解获取器,从当前属性信息中读取字段注解
*/
val annotationGetter = object : AnnotationGetter {
override fun <T : Annotation> getAnnotation(clazz: Class<T>): T? = property?.getAnnotation(clazz)
}
/** /**
* 序列化方法:将源对象转换为目标对象,并根据目标对象的类型写入 JSON。 * 序列化方法:将源对象转换为目标对象,并根据目标对象的类型写入 JSON。
@@ -43,30 +55,11 @@ class JackJsonSerializer<F, T>(
* @param provider 序列化提供者,可选参数。 * @param provider 序列化提供者,可选参数。
*/ */
override fun serialize( override fun serialize(
value: F?, value: T?,
gen: JsonGenerator, gen: JsonGenerator,
provider: SerializerProvider?, provider: SerializerProvider?,
) { ) {
// 执行转换逻辑 jsonConverter.convert(value, JackSonJsonWriter(gen, provider), annotationGetter)
val data: T? = jsonConverter.convert(value, object : AnnotationGetter {
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
})
// 根据目标对象的类型写入对应的 JSON 值
when (data) {
null -> gen.writeNull()
is String -> gen.writeString(data)
is Long -> gen.writeNumber(data)
is Short -> gen.writeNumber(data)
is Byte -> gen.writeNumber(data.toShort())
is Int -> gen.writeNumber(data)
is BigDecimal -> gen.writeNumber(data)
is BigInteger -> gen.writeNumber(data)
is Float -> gen.writeNumber(data)
is Double -> gen.writeNumber(data)
is Boolean -> gen.writeBoolean(data)
else -> throw IllegalArgumentException("not sport data type ${data.javaClass} $data")
}
} }
/** /**
@@ -79,7 +72,7 @@ class JackJsonSerializer<F, T>(
override fun createContextual( override fun createContextual(
prov: SerializerProvider?, prov: SerializerProvider?,
property: BeanProperty?, property: BeanProperty?,
): JsonSerializer<F> { ): JsonSerializer<T> {
return JackJsonSerializer(property, jsonConverter) return JackJsonSerializer(property, this.jsonConverter)
} }
} }
@@ -1,91 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonConverter.kt
* LastUpdate 2026-02-07 22:30:18
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* BaseJsonConverter 是一个通用的 JSON 转换器接口,用于定义对象之间的双向转换逻辑。
*
* @param F 源类型,表示需要被转换的对象类型。
* @param T 目标类型,表示转换后的对象类型。
*/
interface JsonConverter<F, T> {
/**
* 将源对象转换为目标对象。
*
* @param obj 源对象,可能为 null。
* @param annotationGetter 注解获取器,用于获取字段上的注解信息。
* @return 转换后的目标对象,可能为 null。
* @throws Exception 转换过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun convert(obj: F?, annotationGetter: AnnotationGetter): T?
/**
* 将目标对象反向转换为源对象。
*
* @param obj 目标对象,可能为 null。
* @param annotationGetter 注解获取器,用于获取字段上的注解信息。
* @return 反向转换后的源对象,可能为 null。
* @throws Exception 转换过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun deConvert(obj: T?, annotationGetter: AnnotationGetter): F?
/**
* 获取源类型的类型引用。
*
* @return 源类型的 JsonTypeReference 对象。
* @throws Exception 获取过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun getFromType(): JsonTypeReference<F>
/**
* 获取目标类型的类型引用。
*
* @return 目标类型的 JsonTypeReference 对象。
* @throws Exception 获取过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun getToType(): JsonTypeReference<T>
/**
* 获取源类型的原始类。
*
* @return 源类型的 Class 对象。
* @throws Exception 获取过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun getFromClass() = getFromType().getRawType()
/**
* 获取目标类型的原始类。
*
* @return 目标类型的 Class 对象。
* @throws Exception 获取过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun getToClass() = getToType().getRawType()
}
@@ -13,10 +13,10 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
* ProjectName FastBaseMapper.kt * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JsonConverterUtils.kt * CurrentFile JsonConverterUtils.kt
* LastUpdate 2026-10-26 23:22:18 * LastUpdate 2026-11-17 20:11:04
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@file:JvmName("JsonConverterUtils") @file:JvmName("JsonConverterUtils")
@@ -24,61 +24,81 @@
package com.mingliqiye.utils.json.converters.base package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.logger.MingLiLoggerFactory import java.math.BigDecimal
import java.lang.reflect.ParameterizedType import java.math.BigInteger
import java.lang.reflect.Type import com.fasterxml.jackson.core.JsonGenerator as JackSon2JsonGenerator
import com.fasterxml.jackson.databind.module.SimpleModule as JackSon2SimpleModule
import tools.jackson.core.JsonGenerator as JackSon3JsonGenerator
import tools.jackson.databind.module.SimpleModule as JackSon3SimpleModule
val log = MingLiLoggerFactory.getLogger("com.mingliqiye.utils.json.converters.base.JsonConverterUtils")
/** /**
* 获取给定类型的实际类对象。 * 将转换器包装为 Jackson2 的 SimpleModule,注册对应的序列化器与反序列化器。
* *
* @param type 类型对象,可以是Class、ParameterizedType或其他Type的实现。 * @return 注册了当前转换器的 Jackson2 模块
* @return 返回与给定类型对应的Class对象;如果无法解析,则返回null。
*/ */
fun getClass(type: Type?): Class<*>? { fun <T> BaseJsonConverter<T>.getJacksonModule(): JackSon2SimpleModule =
// 尝试将type直接转换为Class类型,如果失败则检查是否为ParameterizedType JackSon2SimpleModule("${getClazz().simpleName}Module")
val clazz: Class<*>? = type as? Class<*> ?: if (type is ParameterizedType) { .addSerializer(getClazz(), JackJsonSerializer(null, this))
// 如果是ParameterizedType,则递归获取其原始类型 .addDeserializer(getClazz(), JackJsonDeserializer(null, this))
getClass(type.rawType)
} else {
null
}
return clazz
}
inline fun <reified T : JsonConverter<*, *>> getJsonConverter(): T = getJsonConverter(T::class.java)
@Suppress("UNCHECKED_CAST")
fun <T : JsonConverter<*, *>> getJsonConverter(clazz: Class<T>): T {
try {
return clazz.getDeclaredMethod(
"getJsonConverter"
).invoke(null) as T
} catch (e: Exception) {
log.error("实现于 JsonConverter<*, *> 的类 必须实现静态方法 JsonConverter<*, *> getJsonConverter()", e)
throw e
}
}
fun <T : BaseJsonConverter<*, *>> com.fasterxml.jackson.databind.ObjectMapper.addJsonConverter(clazz: Class<T>): com.fasterxml.jackson.databind.ObjectMapper =
this.registerModule(getJsonConverter(clazz).getJacksonModule())
@JvmName("inline_addJsonConverter")
inline fun <reified T : BaseJsonConverter<*, *>> com.fasterxml.jackson.databind.ObjectMapper.addJsonConverter(): com.fasterxml.jackson.databind.ObjectMapper =
this.registerModule(getJsonConverter(T::class.java).getJacksonModule())
/** /**
* 创建并返回一个 Jackson 模块,该模块包含自定义的序列化器和反序列化器。 * 将转换器包装为 Jackson3 的 SimpleModule,注册对应的序列化器与反序列化器。
* *
* @return 配置了自定义序列化器和反序列化器的 SimpleModule 对象。 * @return 注册了当前转换器的 Jackson3 模块
*/ */
fun <F, T> JsonConverter<F, T>.getJacksonModule(): com.fasterxml.jackson.databind.module.SimpleModule = fun <T> BaseJsonConverter<T>.getJackson3Module(): JackSon3SimpleModule =
com.fasterxml.jackson.databind.module.SimpleModule("(${getFromClass().name})-(${getToClass().name})") JackSon3SimpleModule("${getClazz().simpleName}Module")
.addSerializer(getFromClass(), JackJsonSerializer(null, this)) .addSerializer(getClazz(), JackJson3Serializer(null, this))
.addDeserializer(getFromClass(), JackJsonDeserializer(null, this)) .addDeserializer(getClazz(), JackJson3Deserializer(null, this))
fun <F, T> JsonConverter<F, T>.getJackson3Module(): tools.jackson.databind.module.SimpleModule =
tools.jackson.databind.module.SimpleModule("(${getFromClass().name})-(${getToClass().name})") /**
.addSerializer(getFromClass(), JackJson3Serializer(null, this)) * 根据 reified 泛型参数获取指定类型的注解。
.addDeserializer(getFromClass(), JackJson3Deserializer(null, this)) *
* @param T 注解类型
* @return 注解实例,不存在时返回null
*/
inline fun <reified T : Annotation> AnnotationGetter.getAnnotation(): T? =
getAnnotation(T::class.java)
/**
* 按数值的实际类型写入 JSON 数字(Jackson3),支持常见数值类型。
*
* @param value 待写入的数值
* @return 当前 JsonGenerator 实例,便于链式调用
*/
fun JackSon3JsonGenerator.writeNumber(value: Number): JackSon3JsonGenerator {
when (value) {
is Long -> this.writeNumber(value)
is Short -> this.writeNumber(value)
is Byte -> this.writeNumber(value.toShort())
is Int -> this.writeNumber(value)
is BigDecimal -> this.writeNumber(value)
is BigInteger -> this.writeNumber(value)
is Float -> this.writeNumber(value)
is Double -> this.writeNumber(value)
}
return this
}
/**
* 按数值的实际类型写入 JSON 数字(Jackson2),支持常见数值类型。
*
* @param value 待写入的数值
* @return 当前 JsonGenerator 实例,便于链式调用
*/
fun JackSon2JsonGenerator.writeNumber(value: Number): JackSon2JsonGenerator {
when (value) {
is Long -> this.writeNumber(value)
is Short -> this.writeNumber(value)
is Byte -> this.writeNumber(value.toShort())
is Int -> this.writeNumber(value)
is BigDecimal -> this.writeNumber(value)
is BigInteger -> this.writeNumber(value)
is Float -> this.writeNumber(value)
is Double -> this.writeNumber(value)
}
return this
}
@@ -0,0 +1,49 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSon3ReaderJudgment.kt
* LastUpdate 2026-11-17 20:29:39
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.judgment
import com.mingliqiye.utils.json.judgment.base.BaseJsonJudgment
import tools.jackson.databind.JsonNode
/**
* 基于 Jackson3 JsonNode 的类型判断实现,各判定属性直接委托给节点自身
*
* @param treeNode 待判断的 Jackson3 JsonNode 节点
*/
open class JackSon3ReaderJudgment(
private val treeNode: JsonNode,
) : BaseJsonJudgment {
override val isObject: Boolean
get() = treeNode.isObject
override val isArray: Boolean
get() = treeNode.isArray
override val isString: Boolean
get() = treeNode.isString
override val isNumber: Boolean
get() = treeNode.isNumber
override val isBoolean: Boolean
get() = treeNode.isBoolean
override val isNull: Boolean
get() = treeNode.isNull
}
@@ -0,0 +1,49 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSonReaderJudgment.kt
* LastUpdate 2026-11-17 20:29:39
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.judgment
import com.fasterxml.jackson.databind.JsonNode
import com.mingliqiye.utils.json.judgment.base.BaseJsonJudgment
/**
* 基于 Jackson2 JsonNode 的类型判断实现,各判定属性直接委托给节点自身
*
* @param treeNode 待判断的 Jackson2 JsonNode 节点
*/
open class JackSonReaderJudgment(
private val treeNode: JsonNode,
) : BaseJsonJudgment {
override val isObject: Boolean
get() = treeNode.isObject
override val isArray: Boolean
get() = treeNode.isArray
override val isString: Boolean
get() = treeNode.isTextual
override val isNumber: Boolean
get() = treeNode.isNumber
override val isBoolean: Boolean
get() = treeNode.isBoolean
override val isNull: Boolean
get() = treeNode.isNull
}
@@ -0,0 +1,51 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonJudgment.kt
* LastUpdate 2026-11-17 20:26:28
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.judgment.base
/**
* JSON 节点类型判断接口,提供当前节点的类型判定属性,默认实现均返回 false
*/
interface BaseJsonJudgment {
/** 当前节点是否为 JSON 对象 */
val isObject: Boolean
get() = false
/** 当前节点是否为 JSON 数组 */
val isArray: Boolean
get() = false
/** 当前节点是否为字符串 */
val isString: Boolean
get() = false
/** 当前节点是否为数字 */
val isNumber: Boolean
get() = false
/** 当前节点是否为布尔值 */
val isBoolean: Boolean
get() = false
/** 当前节点是否为 null */
val isNull: Boolean
get() = false
/** 当前节点是否不为 null */
val isNotNull: Boolean
get() = !isNull
}
@@ -0,0 +1,88 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSon3JsonArrayReader.kt
* LastUpdate 2026-11-17 20:29:39
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.reader
import com.mingliqiye.utils.json.judgment.JackSon3ReaderJudgment
import com.mingliqiye.utils.json.reader.base.BaseJsonArrayReader
import com.mingliqiye.utils.json.reader.base.BaseJsonObjectReader
import tools.jackson.databind.JsonNode
import java.math.BigDecimal
import java.math.BigInteger
/**
* 基于 Jackson3 JsonNode 的 JSON 数组读取器实现,按索引读取各类型值
*
* @param treeNode 待读取的 Jackson3 JsonNode 数组节点
*/
class JackSon3JsonArrayReader(
private val treeNode: JsonNode,
) : BaseJsonArrayReader, JackSon3ReaderJudgment(treeNode) {
override fun getIndexObject(key: Int): BaseJsonObjectReader {
return JackSon3JsonObjectReader(treeNode[key])
}
override fun getIndexArray(key: Int): BaseJsonArrayReader {
return JackSon3JsonArrayReader(treeNode[key])
}
override fun getIndexString(key: Int): String {
return treeNode[key].stringValue()
}
override fun getIndexBoolean(key: Int): Boolean {
return treeNode[key].booleanValue()
}
override fun getIndexByte(key: Int): Byte {
return getIndexShort(key).toByte()
}
override fun getIndexShort(key: Int): Short {
return treeNode[key].shortValue()
}
override fun getIndexInt(key: Int): Int {
return treeNode[key].intValue()
}
override fun getIndexLong(key: Int): Long {
return treeNode[key].longValue()
}
override fun getIndexFloat(key: Int): Float {
return treeNode[key].floatValue()
}
override fun getIndexDouble(key: Int): Double {
return treeNode[key].doubleValue()
}
override fun getIndexBigInteger(key: Int): BigInteger {
return treeNode[key].bigIntegerValue()
}
override fun getIndexBigDecimal(key: Int): BigDecimal {
return treeNode[key].decimalValue()
}
}
@@ -0,0 +1,95 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSon3JsonObjectReader.kt
* LastUpdate 2026-11-17 20:29:39
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.reader
import com.mingliqiye.utils.json.judgment.JackSon3ReaderJudgment
import com.mingliqiye.utils.json.reader.base.BaseJsonArrayReader
import com.mingliqiye.utils.json.reader.base.BaseJsonObjectReader
import tools.jackson.databind.JsonNode
import java.math.BigDecimal
import java.math.BigInteger
/**
* 基于 Jackson3 JsonNode 的 JSON 对象读取器实现,按字段名读取各类型值
*
* @param treeNode 待读取的 Jackson3 JsonNode 对象节点
*/
class JackSon3JsonObjectReader(
private val treeNode: JsonNode,
) : BaseJsonObjectReader, JackSon3ReaderJudgment(treeNode) {
override fun getFieldObject(key: String): BaseJsonObjectReader {
return JackSon3JsonObjectReader(treeNode[key])
}
override fun getFieldArray(key: String): BaseJsonArrayReader {
return JackSon3JsonArrayReader(treeNode[key])
}
override fun getFieldString(key: String): String {
return treeNode[key].asString()
}
override fun getFieldBoolean(key: String): Boolean {
return treeNode[key].booleanValue()
}
override fun getFieldByte(key: String): Byte {
return getFieldShort(key).toByte()
}
override fun getFieldShort(key: String): Short {
return treeNode[key].shortValue()
}
override fun getFieldInt(key: String): Int {
return treeNode[key].intValue()
}
override fun getFieldLong(key: String): Long {
return treeNode[key].longValue()
}
override fun getFieldFloat(key: String): Float {
return treeNode[key].floatValue()
}
override fun getFieldDouble(key: String): Double {
return treeNode[key].doubleValue()
}
override fun getFieldBigInteger(key: String): BigInteger {
return treeNode[key].bigIntegerValue()
}
override fun getFieldBigDecimal(key: String): BigDecimal {
return treeNode[key].decimalValue()
}
override val isObject: Boolean
get() = treeNode.isObject
}
@@ -0,0 +1,89 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSon3JsonReader.kt
* LastUpdate 2026-11-17 20:29:39
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.reader
import com.mingliqiye.utils.json.judgment.JackSon3ReaderJudgment
import com.mingliqiye.utils.json.reader.base.BaseJsonArrayReader
import com.mingliqiye.utils.json.reader.base.BaseJsonObjectReader
import com.mingliqiye.utils.json.reader.base.BaseJsonReader
import tools.jackson.databind.JsonNode
import java.math.BigDecimal
import java.math.BigInteger
/**
* 基于 Jackson3 JsonNode 的 JSON 读取器实现,将节点值读取为各种类型
*
* @param treeNode 待读取的 Jackson3 JsonNode 节点
*/
class JackSon3JsonReader(
private val treeNode: JsonNode,
) : BaseJsonReader, JackSon3ReaderJudgment(treeNode) {
override fun getObject(): BaseJsonObjectReader {
return JackSon3JsonObjectReader(treeNode)
}
override fun getArray(): BaseJsonArrayReader {
return JackSon3JsonArrayReader(treeNode)
}
override fun getString(): String {
return treeNode.asString()
}
override fun getBoolean(): Boolean {
return treeNode.booleanValue()
}
override fun getByte(): Byte {
return getShort().toByte()
}
override fun getShort(): Short {
return treeNode.shortValue()
}
override fun getInt(): Int {
return treeNode.intValue()
}
override fun getLong(): Long {
return treeNode.longValue()
}
override fun getFloat(): Float {
return treeNode.floatValue()
}
override fun getDouble(): Double {
return treeNode.doubleValue()
}
override fun getBigInteger(): BigInteger {
return treeNode.bigIntegerValue()
}
override fun getBigDecimal(): BigDecimal {
return treeNode.decimalValue()
}
}
@@ -0,0 +1,90 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSonJsonArrayReader.kt
* LastUpdate 2026-11-17 20:29:39
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.reader
import com.fasterxml.jackson.databind.JsonNode
import com.mingliqiye.utils.json.judgment.JackSonReaderJudgment
import com.mingliqiye.utils.json.reader.base.BaseJsonArrayReader
import com.mingliqiye.utils.json.reader.base.BaseJsonObjectReader
import java.math.BigDecimal
import java.math.BigInteger
/**
* 基于 Jackson2 JsonNode 的 JSON 数组读取器实现,按索引读取各类型值
*
* @param treeNode 待读取的 Jackson2 JsonNode 数组节点
*/
class JackSonJsonArrayReader(
private val treeNode: JsonNode,
) : BaseJsonArrayReader, JackSonReaderJudgment(treeNode) {
override fun getIndexObject(key: Int): BaseJsonObjectReader {
return JackSonJsonObjectReader(treeNode[key])
}
override fun getIndexArray(key: Int): BaseJsonArrayReader {
return JackSonJsonArrayReader(treeNode[key])
}
override fun getIndexString(key: Int): String {
return treeNode[key].textValue()
}
override fun getIndexBoolean(key: Int): Boolean {
return treeNode[key].booleanValue()
}
override fun getIndexByte(key: Int): Byte {
return getIndexShort(key).toByte()
}
override fun getIndexShort(key: Int): Short {
return treeNode[key].shortValue()
}
override fun getIndexInt(key: Int): Int {
return treeNode[key].intValue()
}
override fun getIndexLong(key: Int): Long {
return treeNode[key].longValue()
}
override fun getIndexFloat(key: Int): Float {
return treeNode[key].floatValue()
}
override fun getIndexDouble(key: Int): Double {
return treeNode[key].doubleValue()
}
override fun getIndexBigInteger(key: Int): BigInteger {
return treeNode[key].bigIntegerValue()
}
override fun getIndexBigDecimal(key: Int): BigDecimal {
return treeNode[key].decimalValue()
}
}
@@ -0,0 +1,95 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSonJsonObjectReader.kt
* LastUpdate 2026-11-17 20:29:39
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.reader
import com.fasterxml.jackson.databind.JsonNode
import com.mingliqiye.utils.json.judgment.JackSonReaderJudgment
import com.mingliqiye.utils.json.reader.base.BaseJsonArrayReader
import com.mingliqiye.utils.json.reader.base.BaseJsonObjectReader
import java.math.BigDecimal
import java.math.BigInteger
/**
* 基于 Jackson2 JsonNode 的 JSON 对象读取器实现,按字段名读取各类型值
*
* @param treeNode 待读取的 Jackson2 JsonNode 对象节点
*/
class JackSonJsonObjectReader(
private val treeNode: JsonNode,
) : BaseJsonObjectReader, JackSonReaderJudgment(treeNode) {
override fun getFieldObject(key: String): BaseJsonObjectReader {
return JackSonJsonObjectReader(treeNode[key])
}
override fun getFieldArray(key: String): BaseJsonArrayReader {
return JackSonJsonArrayReader(treeNode[key])
}
override fun getFieldString(key: String): String {
return treeNode[key].textValue()
}
override fun getFieldBoolean(key: String): Boolean {
return treeNode[key].booleanValue()
}
override fun getFieldByte(key: String): Byte {
return getFieldShort(key).toByte()
}
override fun getFieldShort(key: String): Short {
return treeNode[key].shortValue()
}
override fun getFieldInt(key: String): Int {
return treeNode[key].intValue()
}
override fun getFieldLong(key: String): Long {
return treeNode[key].longValue()
}
override fun getFieldFloat(key: String): Float {
return treeNode[key].floatValue()
}
override fun getFieldDouble(key: String): Double {
return treeNode[key].doubleValue()
}
override fun getFieldBigInteger(key: String): BigInteger {
return treeNode[key].bigIntegerValue()
}
override fun getFieldBigDecimal(key: String): BigDecimal {
return treeNode[key].decimalValue()
}
override val isObject: Boolean
get() = treeNode.isObject
}
@@ -0,0 +1,89 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSonJsonReader.kt
* LastUpdate 2026-11-17 20:29:39
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.reader
import com.fasterxml.jackson.databind.JsonNode
import com.mingliqiye.utils.json.judgment.JackSonReaderJudgment
import com.mingliqiye.utils.json.reader.base.BaseJsonArrayReader
import com.mingliqiye.utils.json.reader.base.BaseJsonObjectReader
import com.mingliqiye.utils.json.reader.base.BaseJsonReader
import java.math.BigDecimal
import java.math.BigInteger
/**
* 基于 Jackson2 JsonNode 的 JSON 读取器实现,将节点值读取为各种类型
*
* @param treeNode 待读取的 Jackson2 JsonNode 节点
*/
class JackSonJsonReader(
private val treeNode: JsonNode,
) : BaseJsonReader, JackSonReaderJudgment(treeNode) {
override fun getObject(): BaseJsonObjectReader {
return JackSonJsonObjectReader(treeNode)
}
override fun getArray(): BaseJsonArrayReader {
return JackSonJsonArrayReader(treeNode)
}
override fun getString(): String {
return treeNode.asText()
}
override fun getBoolean(): Boolean {
return treeNode.booleanValue()
}
override fun getByte(): Byte {
return getShort().toByte()
}
override fun getShort(): Short {
return treeNode.shortValue()
}
override fun getInt(): Int {
return treeNode.intValue()
}
override fun getLong(): Long {
return treeNode.longValue()
}
override fun getFloat(): Float {
return treeNode.floatValue()
}
override fun getDouble(): Double {
return treeNode.doubleValue()
}
override fun getBigInteger(): BigInteger {
return treeNode.bigIntegerValue()
}
override fun getBigDecimal(): BigDecimal {
return treeNode.decimalValue()
}
}
@@ -0,0 +1,167 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonArrayReader.kt
* LastUpdate 2026-11-17 19:32:34
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.reader.base
import com.mingliqiye.utils.exception.JsonParserException
import java.math.BigDecimal
import java.math.BigInteger
/**
* JSON 数组读取器接口,按索引读取数组中的各类型值。
*
* 直接读取当前节点的 getXxx 方法默认抛出 [JsonParserException],应使用 getIndexXxx 系列方法。
*/
interface BaseJsonArrayReader : BaseJsonReader {
/** 数组读取器不支持直接读取为对象,调用时抛出 [JsonParserException] */
override fun getObject(): BaseJsonObjectReader =
throw JsonParserException("not supported getObject on BaseJsonArrayReader")
/** 数组读取器不支持直接读取为数组,调用时抛出 [JsonParserException] */
override fun getArray(): BaseJsonArrayReader =
throw JsonParserException("not supported getArray on BaseJsonArrayReader")
/** 数组读取器不支持直接读取为字符串,调用时抛出 [JsonParserException] */
override fun getString(): String =
throw JsonParserException("not supported getString on BaseJsonArrayReader")
/** 数组读取器不支持直接读取为布尔值,调用时抛出 [JsonParserException] */
override fun getBoolean(): Boolean =
throw JsonParserException("not supported getBoolean on BaseJsonArrayReader")
/** 数组读取器不支持直接读取为 Byte,调用时抛出 [JsonParserException] */
override fun getByte(): Byte =
throw JsonParserException("not supported getByte on BaseJsonArrayReader")
/** 数组读取器不支持直接读取为 Short,调用时抛出 [JsonParserException] */
override fun getShort(): Short =
throw JsonParserException("not supported getShort on BaseJsonArrayReader")
/** 数组读取器不支持直接读取为 Int,调用时抛出 [JsonParserException] */
override fun getInt(): Int =
throw JsonParserException("not supported getInt on BaseJsonArrayReader")
/** 数组读取器不支持直接读取为 Long,调用时抛出 [JsonParserException] */
override fun getLong(): Long =
throw JsonParserException("not supported getLong on BaseJsonArrayReader")
/** 数组读取器不支持直接读取为 Float,调用时抛出 [JsonParserException] */
override fun getFloat(): Float =
throw JsonParserException("not supported getFloat on BaseJsonArrayReader")
/** 数组读取器不支持直接读取为 Double,调用时抛出 [JsonParserException] */
override fun getDouble(): Double =
throw JsonParserException("not supported getDouble on BaseJsonArrayReader")
/** 数组读取器不支持直接读取为 BigInteger,调用时抛出 [JsonParserException] */
override fun getBigInteger(): BigInteger =
throw JsonParserException("not supported getBigInteger on BaseJsonArrayReader")
/** 数组读取器不支持直接读取为 BigDecimal,调用时抛出 [JsonParserException] */
override fun getBigDecimal(): BigDecimal =
throw JsonParserException("not supported getBigDecimal on BaseJsonArrayReader")
/**
* 读取指定索引的对象元素
*
* @param key 数组索引
* @return 元素对应的 JSON 对象读取器
*/
fun getIndexObject(key: Int): BaseJsonObjectReader
/**
* 读取指定索引的数组元素
*
* @param key 数组索引
* @return 元素对应的 JSON 数组读取器
*/
fun getIndexArray(key: Int): BaseJsonArrayReader
/**
* 读取指定索引的字符串元素
*
* @param key 数组索引
* @return 元素的字符串值
*/
fun getIndexString(key: Int): String
/**
* 读取指定索引的布尔元素
*
* @param key 数组索引
* @return 元素的布尔值
*/
fun getIndexBoolean(key: Int): Boolean
/**
* 读取指定索引的 Byte 数值元素
*
* @param key 数组索引
* @return 元素的 Byte 数值
*/
fun getIndexByte(key: Int): Byte
/**
* 读取指定索引的 Short 数值元素
*
* @param key 数组索引
* @return 元素的 Short 数值
*/
fun getIndexShort(key: Int): Short
/**
* 读取指定索引的 Int 数值元素
*
* @param key 数组索引
* @return 元素的 Int 数值
*/
fun getIndexInt(key: Int): Int
/**
* 读取指定索引的 Long 数值元素
*
* @param key 数组索引
* @return 元素的 Long 数值
*/
fun getIndexLong(key: Int): Long
/**
* 读取指定索引的 Float 数值元素
*
* @param key 数组索引
* @return 元素的 Float 数值
*/
fun getIndexFloat(key: Int): Float
/**
* 读取指定索引的 Double 数值元素
*
* @param key 数组索引
* @return 元素的 Double 数值
*/
fun getIndexDouble(key: Int): Double
/**
* 读取指定索引的 BigInteger 数值元素
*
* @param key 数组索引
* @return 元素的 BigInteger 数值
*/
fun getIndexBigInteger(key: Int): BigInteger
/**
* 读取指定索引的 BigDecimal 数值元素
*
* @param key 数组索引
* @return 元素的 BigDecimal 数值
*/
fun getIndexBigDecimal(key: Int): BigDecimal
}
@@ -0,0 +1,171 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonObjectReader.kt
* LastUpdate 2026-11-17 19:32:34
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.reader.base
import com.mingliqiye.utils.exception.JsonParserException
import java.math.BigDecimal
import java.math.BigInteger
/**
* JSON 对象读取器接口,按字段名读取对象中的各类型值。
*
* 直接读取当前节点的 getXxx 方法默认抛出 [JsonParserException],应使用 getFieldXxx 系列方法。
*/
interface BaseJsonObjectReader : BaseJsonReader {
override val isObject: Boolean
get() = true
/** 对象读取器不支持直接读取为对象,调用时抛出 [JsonParserException] */
override fun getObject(): BaseJsonObjectReader =
throw JsonParserException("not supported getObject on BaseJsonObjectReader")
/** 对象读取器不支持直接读取为数组,调用时抛出 [JsonParserException] */
override fun getArray(): BaseJsonArrayReader =
throw JsonParserException("not supported getArray on BaseJsonObjectReader")
/** 对象读取器不支持直接读取为字符串,调用时抛出 [JsonParserException] */
override fun getString(): String =
throw JsonParserException("not supported getString on BaseJsonObjectReader")
/** 对象读取器不支持直接读取为布尔值,调用时抛出 [JsonParserException] */
override fun getBoolean(): Boolean =
throw JsonParserException("not supported getBoolean on BaseJsonObjectReader")
/** 对象读取器不支持直接读取为 Byte,调用时抛出 [JsonParserException] */
override fun getByte(): Byte =
throw JsonParserException("not supported getByte on BaseJsonObjectReader")
/** 对象读取器不支持直接读取为 Short,调用时抛出 [JsonParserException] */
override fun getShort(): Short =
throw JsonParserException("not supported getShort on BaseJsonObjectReader")
/** 对象读取器不支持直接读取为 Int,调用时抛出 [JsonParserException] */
override fun getInt(): Int =
throw JsonParserException("not supported getInt on BaseJsonObjectReader")
/** 对象读取器不支持直接读取为 Long,调用时抛出 [JsonParserException] */
override fun getLong(): Long =
throw JsonParserException("not supported getLong on BaseJsonObjectReader")
/** 对象读取器不支持直接读取为 Float,调用时抛出 [JsonParserException] */
override fun getFloat(): Float =
throw JsonParserException("not supported getFloat on BaseJsonObjectReader")
/** 对象读取器不支持直接读取为 Double,调用时抛出 [JsonParserException] */
override fun getDouble(): Double =
throw JsonParserException("not supported getDouble on BaseJsonObjectReader")
/** 对象读取器不支持直接读取为 BigInteger,调用时抛出 [JsonParserException] */
override fun getBigInteger(): BigInteger =
throw JsonParserException("not supported getBigInteger on BaseJsonObjectReader")
/** 对象读取器不支持直接读取为 BigDecimal,调用时抛出 [JsonParserException] */
override fun getBigDecimal(): BigDecimal =
throw JsonParserException("not supported getBigDecimal on BaseJsonObjectReader")
/**
* 读取指定字段的对象值
*
* @param key 字段名
* @return 字段对应的 JSON 对象读取器
*/
fun getFieldObject(key: String): BaseJsonObjectReader
/**
* 读取指定字段的数组值
*
* @param key 字段名
* @return 字段对应的 JSON 数组读取器
*/
fun getFieldArray(key: String): BaseJsonArrayReader
/**
* 读取指定字段的字符串值
*
* @param key 字段名
* @return 字段的字符串值
*/
fun getFieldString(key: String): String
/**
* 读取指定字段的布尔值
*
* @param key 字段名
* @return 字段的布尔值
*/
fun getFieldBoolean(key: String): Boolean
/**
* 读取指定字段的 Byte 数值
*
* @param key 字段名
* @return 字段的 Byte 数值
*/
fun getFieldByte(key: String): Byte
/**
* 读取指定字段的 Short 数值
*
* @param key 字段名
* @return 字段的 Short 数值
*/
fun getFieldShort(key: String): Short
/**
* 读取指定字段的 Int 数值
*
* @param key 字段名
* @return 字段的 Int 数值
*/
fun getFieldInt(key: String): Int
/**
* 读取指定字段的 Long 数值
*
* @param key 字段名
* @return 字段的 Long 数值
*/
fun getFieldLong(key: String): Long
/**
* 读取指定字段的 Float 数值
*
* @param key 字段名
* @return 字段的 Float 数值
*/
fun getFieldFloat(key: String): Float
/**
* 读取指定字段的 Double 数值
*
* @param key 字段名
* @return 字段的 Double 数值
*/
fun getFieldDouble(key: String): Double
/**
* 读取指定字段的 BigInteger 数值
*
* @param key 字段名
* @return 字段的 BigInteger 数值
*/
fun getFieldBigInteger(key: String): BigInteger
/**
* 读取指定字段的 BigDecimal 数值
*
* @param key 字段名
* @return 字段的 BigDecimal 数值
*/
fun getFieldBigDecimal(key: String): BigDecimal
}
@@ -0,0 +1,106 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonReader.kt
* LastUpdate 2026-11-17 20:26:28
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.reader.base
import com.mingliqiye.utils.json.judgment.base.BaseJsonJudgment
import java.math.BigDecimal
import java.math.BigInteger
/**
* JSON 读取器基础接口,继承类型判断能力,定义将当前节点读取为各种类型值的方法
*/
interface BaseJsonReader : BaseJsonJudgment {
/**
* 将当前节点作为对象读取器返回
*
* @return JSON 对象读取器
*/
fun getObject(): BaseJsonObjectReader
/**
* 将当前节点作为数组读取器返回
*
* @return JSON 数组读取器
*/
fun getArray(): BaseJsonArrayReader
/**
* 读取当前节点的字符串值
*
* @return 字符串值
*/
fun getString(): String
/**
* 读取当前节点的布尔值
*
* @return 布尔值
*/
fun getBoolean(): Boolean
/**
* 读取当前节点的 Byte 数值
*
* @return Byte 数值
*/
fun getByte(): Byte
/**
* 读取当前节点的 Short 数值
*
* @return Short 数值
*/
fun getShort(): Short
/**
* 读取当前节点的 Int 数值
*
* @return Int 数值
*/
fun getInt(): Int
/**
* 读取当前节点的 Long 数值
*
* @return Long 数值
*/
fun getLong(): Long
/**
* 读取当前节点的 Float 数值
*
* @return Float 数值
*/
fun getFloat(): Float
/**
* 读取当前节点的 Double 数值
*
* @return Double 数值
*/
fun getDouble(): Double
/**
* 读取当前节点的 BigInteger 数值
*
* @return BigInteger 数值
*/
fun getBigInteger(): BigInteger
/**
* 读取当前节点的 BigDecimal 数值
*
* @return BigDecimal 数值
*/
fun getBigDecimal(): BigDecimal
}
@@ -0,0 +1,75 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSon3ArrayWriter.kt
* LastUpdate 2026-11-17 19:34:28
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.witer
import com.mingliqiye.utils.json.converters.base.writeNumber
import com.mingliqiye.utils.json.witer.base.BaseJsonArrayWriter
import com.mingliqiye.utils.json.witer.base.BaseJsonObjectWriter
import tools.jackson.core.JsonGenerator
import tools.jackson.databind.SerializationContext
/**
* 基于 Jackson3 JsonGenerator 的 JSON 数组写入器实现,向数组追加各类型元素
*
* @param jsonGenerator Jackson3 的 JSON 生成器
* @param serializationContext 序列化上下文
*/
class JackSon3ArrayWriter(
private val jsonGenerator: JsonGenerator,
private val serializationContext: SerializationContext,
) : BaseJsonArrayWriter {
override fun addNull(): JackSon3ArrayWriter {
jsonGenerator.writeNull()
return this
}
override fun addString(value: String): JackSon3ArrayWriter {
jsonGenerator.writeString(value)
return this
}
override fun addNumber(value: Number): JackSon3ArrayWriter {
jsonGenerator.writeNumber(value)
return this
}
override fun addBoolean(value: Boolean): JackSon3ArrayWriter {
jsonGenerator.writeBoolean(value)
return this
}
override fun addObject(value: (BaseJsonObjectWriter) -> Unit): JackSon3ArrayWriter {
jsonGenerator.writeStartObject()
value(JackSon3ObjectWriter(jsonGenerator, serializationContext))
jsonGenerator.writeEndObject()
return this
}
override fun addArray(value: (BaseJsonArrayWriter) -> Unit): JackSon3ArrayWriter {
jsonGenerator.writeStartArray()
value(JackSon3ArrayWriter(jsonGenerator, serializationContext))
jsonGenerator.writeEndArray()
return this
}
}
@@ -0,0 +1,76 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSon3JsonWriter.kt
* LastUpdate 2026-11-17 19:32:34
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.witer
import com.mingliqiye.utils.json.converters.base.writeNumber
import com.mingliqiye.utils.json.witer.base.BaseJsonArrayWriter
import com.mingliqiye.utils.json.witer.base.BaseJsonObjectWriter
import com.mingliqiye.utils.json.witer.base.BaseJsonWriter
import tools.jackson.core.JsonGenerator
import tools.jackson.databind.SerializationContext
/**
* 基于 Jackson3 JsonGenerator 的 JSON 写入器实现,对象/数组写入时自动补全起止标记
*
* @param jsonGenerator Jackson3 的 JSON 生成器
* @param serializationContext 序列化上下文
*/
class JackSon3JsonWriter(
private val jsonGenerator: JsonGenerator,
private val serializationContext: SerializationContext,
) : BaseJsonWriter {
override fun setObject(objCall: (BaseJsonObjectWriter) -> BaseJsonObjectWriter) {
jsonGenerator.writeStartObject()
objCall(
JackSon3ObjectWriter(
jsonGenerator,
serializationContext,
)
)
jsonGenerator.writeEndObject()
}
override fun setArray(arrayCall: (BaseJsonArrayWriter) -> BaseJsonArrayWriter) {
jsonGenerator.writeStartArray()
arrayCall(JackSon3ArrayWriter(jsonGenerator, serializationContext))
jsonGenerator.writeEndArray()
}
override fun setString(string: String) {
jsonGenerator.writeString(string)
}
override fun setNumber(number: Number) {
jsonGenerator.writeNumber(number)
}
override fun setBoolean(boolean: Boolean) {
jsonGenerator.writeBoolean(boolean)
}
override fun setNull() {
jsonGenerator.writeNull()
}
}
@@ -0,0 +1,101 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSon3ObjectWriter.kt
* LastUpdate 2026-11-17 19:32:34
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.witer
import com.mingliqiye.utils.json.converters.base.writeNumber
import com.mingliqiye.utils.json.witer.base.BaseJsonArrayWriter
import com.mingliqiye.utils.json.witer.base.BaseJsonObjectWriter
import tools.jackson.core.JsonGenerator
import tools.jackson.databind.SerializationContext
/**
* 基于 Jackson3 JsonGenerator 的 JSON 对象写入器实现,按字段名追加各类型值
*
* @param jsonGenerator Jackson3 的 JSON 生成器
* @param serializationContext 序列化上下文
*/
class JackSon3ObjectWriter(
private val jsonGenerator: JsonGenerator,
private val serializationContext: SerializationContext,
) : BaseJsonObjectWriter {
/**
* 写入字段名
*
* @param name 字段名
* @return 当前 JsonGenerator 实例,便于链式调用
*/
fun writeName(name: String): JsonGenerator = jsonGenerator.writeName(name)
override fun addNull(name: String): BaseJsonObjectWriter {
writeName(name)
return this
}
override fun addString(
name: String,
value: String,
): BaseJsonObjectWriter {
writeName(name).writeString(value)
return this
}
override fun addNumber(
name: String,
value: Number,
): BaseJsonObjectWriter {
writeName(name).writeNumber(value)
return this
}
override fun addBoolean(
name: String,
value: Boolean,
): BaseJsonObjectWriter {
writeName(name).writeBoolean(value)
return this
}
override fun addObject(
name: String,
valueCaller: (BaseJsonObjectWriter) -> Unit,
): BaseJsonObjectWriter {
writeName(name)
jsonGenerator.writeStartObject()
valueCaller(JackSon3ObjectWriter(jsonGenerator, serializationContext))
jsonGenerator.writeEndObject()
return this
}
override fun addArray(
name: String,
valueCaller: (BaseJsonArrayWriter) -> Unit,
): BaseJsonObjectWriter {
writeName(name)
jsonGenerator.writeStartArray()
valueCaller(JackSon3ArrayWriter(jsonGenerator, serializationContext))
jsonGenerator.writeEndArray()
return this
}
}
@@ -0,0 +1,75 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSonArrayWriter.kt
* LastUpdate 2026-11-17 20:01:56
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.witer
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.SerializerProvider
import com.mingliqiye.utils.json.converters.base.writeNumber
import com.mingliqiye.utils.json.witer.base.BaseJsonArrayWriter
import com.mingliqiye.utils.json.witer.base.BaseJsonObjectWriter
/**
* 基于 Jackson2 JsonGenerator 的 JSON 数组写入器实现,向数组追加各类型元素
*
* @param jsonGenerator Jackson2 的 JSON 生成器
* @param serializationContext 序列化上下文,可为null
*/
class JackSonArrayWriter(
private val jsonGenerator: JsonGenerator,
private val serializationContext: SerializerProvider?,
) : BaseJsonArrayWriter {
override fun addNull(): JackSonArrayWriter {
jsonGenerator.writeNull()
return this
}
override fun addString(value: String): JackSonArrayWriter {
jsonGenerator.writeString(value)
return this
}
override fun addNumber(value: Number): JackSonArrayWriter {
jsonGenerator.writeNumber(value)
return this
}
override fun addBoolean(value: Boolean): JackSonArrayWriter {
jsonGenerator.writeBoolean(value)
return this
}
override fun addObject(value: (BaseJsonObjectWriter) -> Unit): JackSonArrayWriter {
jsonGenerator.writeStartObject()
value(JackSonObjectWriter(jsonGenerator, serializationContext))
jsonGenerator.writeEndObject()
return this
}
override fun addArray(value: (BaseJsonArrayWriter) -> Unit): JackSonArrayWriter {
jsonGenerator.writeStartArray()
value(JackSonArrayWriter(jsonGenerator, serializationContext))
jsonGenerator.writeEndArray()
return this
}
}
@@ -0,0 +1,76 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSonJsonWriter.kt
* LastUpdate 2026-11-17 20:01:48
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.witer
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.SerializerProvider
import com.mingliqiye.utils.json.converters.base.writeNumber
import com.mingliqiye.utils.json.witer.base.BaseJsonArrayWriter
import com.mingliqiye.utils.json.witer.base.BaseJsonObjectWriter
import com.mingliqiye.utils.json.witer.base.BaseJsonWriter
/**
* 基于 Jackson2 JsonGenerator 的 JSON 写入器实现,对象/数组写入时自动补全起止标记
*
* @param jsonGenerator Jackson2 的 JSON 生成器
* @param serializationContext 序列化上下文,可为null
*/
class JackSonJsonWriter(
private val jsonGenerator: JsonGenerator,
private val serializationContext: SerializerProvider?,
) : BaseJsonWriter {
override fun setObject(objCall: (BaseJsonObjectWriter) -> BaseJsonObjectWriter) {
jsonGenerator.writeStartObject()
objCall(
JackSonObjectWriter(
jsonGenerator,
serializationContext,
)
)
jsonGenerator.writeEndObject()
}
override fun setArray(arrayCall: (BaseJsonArrayWriter) -> BaseJsonArrayWriter) {
jsonGenerator.writeStartArray()
arrayCall(JackSonArrayWriter(jsonGenerator, serializationContext))
jsonGenerator.writeEndArray()
}
override fun setString(string: String) {
jsonGenerator.writeString(string)
}
override fun setNumber(number: Number) {
jsonGenerator.writeNumber(number)
}
override fun setBoolean(boolean: Boolean) {
jsonGenerator.writeBoolean(boolean)
}
override fun setNull() {
jsonGenerator.writeNull()
}
}
@@ -0,0 +1,95 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSonObjectWriter.kt
* LastUpdate 2026-11-17 20:06:55
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.witer
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.SerializerProvider
import com.mingliqiye.utils.json.converters.base.writeNumber
import com.mingliqiye.utils.json.witer.base.BaseJsonArrayWriter
import com.mingliqiye.utils.json.witer.base.BaseJsonObjectWriter
/**
* 基于 Jackson2 JsonGenerator 的 JSON 对象写入器实现,按字段名追加各类型值
*
* @param jsonGenerator Jackson2 的 JSON 生成器
* @param serializationContext 序列化上下文,可为null
*/
class JackSonObjectWriter(
private val jsonGenerator: JsonGenerator,
private val serializationContext: SerializerProvider?,
) : BaseJsonObjectWriter {
override fun addNull(name: String): BaseJsonObjectWriter {
jsonGenerator.writeNullField(name)
return this
}
override fun addString(
name: String,
value: String,
): BaseJsonObjectWriter {
jsonGenerator.writeStringField(name, value)
return this
}
override fun addNumber(
name: String,
value: Number,
): BaseJsonObjectWriter {
jsonGenerator.writeFieldName(name)
jsonGenerator.writeNumber(value)
return this
}
override fun addBoolean(
name: String,
value: Boolean,
): BaseJsonObjectWriter {
jsonGenerator.writeBooleanField(name, value)
return this
}
override fun addObject(
name: String,
valueCaller: (BaseJsonObjectWriter) -> Unit,
): BaseJsonObjectWriter {
jsonGenerator.writeFieldName(name)
jsonGenerator.writeStartObject()
valueCaller(JackSonObjectWriter(jsonGenerator, serializationContext))
jsonGenerator.writeEndObject()
return this
}
override fun addArray(
name: String,
valueCaller: (BaseJsonArrayWriter) -> Unit,
): BaseJsonObjectWriter {
jsonGenerator.writeFieldName(name)
jsonGenerator.writeStartArray()
valueCaller(JackSonArrayWriter(jsonGenerator, serializationContext))
jsonGenerator.writeEndArray()
return this
}
}
@@ -0,0 +1,122 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonArrayWriter.kt
* LastUpdate 2026-11-17 19:43:44
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.witer.base
import com.mingliqiye.utils.exception.JsonFormatException
/**
* JSON 数组写入器接口,向数组中追加各类型元素,支持链式调用。
*
* 直接设置当前节点的 setXxx 方法默认抛出 [JsonFormatException],应使用 addXxx 系列方法。
*/
interface BaseJsonArrayWriter : BaseJsonWriter {
/** 数组写入器不支持直接设置为对象,调用时抛出 [JsonFormatException] */
override fun setObject(objCall: (BaseJsonObjectWriter) -> BaseJsonObjectWriter) =
throw JsonFormatException("setObject is not supported on BaseJsonArrayWriter")
/** 数组写入器不支持直接设置为数组,调用时抛出 [JsonFormatException] */
override fun setArray(arrayCall: (BaseJsonArrayWriter) -> BaseJsonArrayWriter) =
throw JsonFormatException("setArray is not supported on BaseJsonArrayWriter")
/** 数组写入器不支持直接设置为字符串,调用时抛出 [JsonFormatException] */
override fun setString(string: String) =
throw JsonFormatException("setString is not supported on BaseJsonArrayWriter")
/** 数组写入器不支持直接设置为数值,调用时抛出 [JsonFormatException] */
override fun setNumber(number: Number) =
throw JsonFormatException("setNumber is not supported on BaseJsonArrayWriter")
/** 数组写入器不支持直接设置为布尔值,调用时抛出 [JsonFormatException] */
override fun setBoolean(boolean: Boolean) =
throw JsonFormatException("setBoolean is not supported on BaseJsonArrayWriter")
/** 数组写入器不支持直接设置为 null,调用时抛出 [JsonFormatException] */
override fun setNull() = throw JsonFormatException("setNull is not supported on BaseJsonArrayWriter")
override val isArray
get() = true
/**
* 追加 null 元素
*
* @return 当前数组写入器,便于链式调用
*/
fun addNull(): BaseJsonArrayWriter
/**
* 追加字符串元素
*
* @param value 字符串值
* @return 当前数组写入器,便于链式调用
*/
fun addString(value: String): BaseJsonArrayWriter
/**
* 追加数值元素
*
* @param value 数值
* @return 当前数组写入器,便于链式调用
*/
fun addNumber(value: Number): BaseJsonArrayWriter
/**
* 追加布尔元素
*
* @param value 布尔值
* @return 当前数组写入器,便于链式调用
*/
fun addBoolean(value: Boolean): BaseJsonArrayWriter
/**
* 追加对象元素,通过回调填充子对象
*
* @param value 子对象写入回调
* @return 当前数组写入器,便于链式调用
*/
fun addObject(value: (BaseJsonObjectWriter) -> Unit): BaseJsonArrayWriter
/**
* 追加数组元素,通过回调填充子数组
*
* @param value 子数组写入回调
* @return 当前数组写入器,便于链式调用
*/
fun addArray(value: (BaseJsonArrayWriter) -> Unit): BaseJsonArrayWriter
/**
* 追加字符串元素,[addString] 的简写
*
* @param value 字符串值
* @return 当前数组写入器,便于链式调用
*/
fun add(value: String): BaseJsonArrayWriter = addString(value)
/**
* 追加数值元素,[addNumber] 的简写
*
* @param value 数值
* @return 当前数组写入器,便于链式调用
*/
fun add(value: Number): BaseJsonArrayWriter = addNumber(value)
/**
* 追加布尔元素,[addBoolean] 的简写
*
* @param value 布尔值
* @return 当前数组写入器,便于链式调用
*/
fun add(value: Boolean): BaseJsonArrayWriter = addBoolean(value)
}
@@ -0,0 +1,132 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonObjectWriter.kt
* LastUpdate 2026-11-17 18:39:06
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.witer.base
import com.mingliqiye.utils.exception.JsonFormatException
/**
* JSON 对象写入器接口,按字段名向对象中追加各类型值,支持链式调用。
*
* 直接设置当前节点的 setXxx 方法默认抛出 [JsonFormatException],应使用 addXxx 系列方法。
*/
interface BaseJsonObjectWriter : BaseJsonWriter {
override val isObject: Boolean
get() = true
/** 对象写入器不支持直接设置为对象,调用时抛出 [JsonFormatException] */
override fun setObject(objCall: (BaseJsonObjectWriter) -> BaseJsonObjectWriter) =
throw JsonFormatException("setObject is not supported on BaseJsonObjectWriter")
/** 对象写入器不支持直接设置为数组,调用时抛出 [JsonFormatException] */
override fun setArray(arrayCall: (BaseJsonArrayWriter) -> BaseJsonArrayWriter) =
throw JsonFormatException("setArray is not supported on BaseJsonObjectWriter")
/** 对象写入器不支持直接设置为字符串,调用时抛出 [JsonFormatException] */
override fun setString(string: String) =
throw JsonFormatException("setString is not supported on BaseJsonObjectWriter")
/** 对象写入器不支持直接设置为数值,调用时抛出 [JsonFormatException] */
override fun setNumber(number: Number) =
throw JsonFormatException("setNumber is not supported on BaseJsonObjectWriter")
/** 对象写入器不支持直接设置为布尔值,调用时抛出 [JsonFormatException] */
override fun setBoolean(boolean: Boolean) =
throw JsonFormatException("setBoolean is not supported on BaseJsonObjectWriter")
/** 对象写入器不支持直接设置为 null,调用时抛出 [JsonFormatException] */
override fun setNull() = throw JsonFormatException("setNull is not supported on BaseJsonObjectWriter")
/**
* 追加值为 null 的字段
*
* @param name 字段名
* @return 当前对象写入器,便于链式调用
*/
fun addNull(name: String): BaseJsonObjectWriter
/**
* 追加字符串字段
*
* @param name 字段名
* @param value 字符串值
* @return 当前对象写入器,便于链式调用
*/
fun addString(name: String, value: String): BaseJsonObjectWriter
/**
* 追加数值字段
*
* @param name 字段名
* @param value 数值
* @return 当前对象写入器,便于链式调用
*/
fun addNumber(name: String, value: Number): BaseJsonObjectWriter
/**
* 追加布尔字段
*
* @param name 字段名
* @param value 布尔值
* @return 当前对象写入器,便于链式调用
*/
fun addBoolean(name: String, value: Boolean): BaseJsonObjectWriter
/**
* 追加对象字段,通过回调填充子对象
*
* @param name 字段名
* @param valueCaller 子对象写入回调
* @return 当前对象写入器,便于链式调用
*/
fun addObject(name: String, valueCaller: (BaseJsonObjectWriter) -> Unit): BaseJsonObjectWriter
/**
* 追加数组字段,通过回调填充数组元素
*
* @param name 字段名
* @param valueCaller 数组写入回调
* @return 当前对象写入器,便于链式调用
*/
fun addArray(name: String, valueCaller: (BaseJsonArrayWriter) -> Unit): BaseJsonObjectWriter
/**
* 追加字符串字段,[addString] 的简写
*
* @param name 字段名
* @param value 字符串值
* @return 当前对象写入器,便于链式调用
*/
fun add(name: String, value: String): BaseJsonObjectWriter = addString(name, value)
/**
* 追加数值字段,[addNumber] 的简写
*
* @param name 字段名
* @param value 数值
* @return 当前对象写入器,便于链式调用
*/
fun add(name: String, value: Number): BaseJsonObjectWriter = addNumber(name, value)
/**
* 追加布尔字段,[addBoolean] 的简写
*
* @param name 字段名
* @param value 布尔值
* @return 当前对象写入器,便于链式调用
*/
fun add(name: String, value: Boolean): BaseJsonObjectWriter = addBoolean(name, value)
}
@@ -0,0 +1,71 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonWriter.kt
* LastUpdate 2026-11-17 21:10:29
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.witer.base
import com.mingliqiye.utils.json.judgment.base.BaseJsonJudgment
/**
* JSON 写入器基础接口,继承类型判断能力,定义将当前节点写为各种类型值的方法
*/
interface BaseJsonWriter : BaseJsonJudgment {
/**
* 写入一个 JSON 对象,通过回调填充对象字段
*
* @param objCall 对象写入回调,接收对象写入器并返回它
*/
fun setObject(objCall: (BaseJsonObjectWriter) -> BaseJsonObjectWriter)
/**
* 写入一个 JSON 数组,通过回调填充数组元素
*
* @param arrayCall 数组写入回调,接收数组写入器并返回它
*/
fun setArray(arrayCall: (BaseJsonArrayWriter) -> BaseJsonArrayWriter)
/**
* 写入字符串值
*
* @param string 待写入的字符串
*/
fun setString(string: String)
/**
* 写入数值
*
* @param number 待写入的数值
*/
fun setNumber(number: Number)
/**
* 写入布尔值
*
* @param boolean 待写入的布尔值
*/
fun setBoolean(boolean: Boolean)
/**
* 写入 null 值
*/
fun setNull()
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile MingLiLogger.kt * CurrentFile MingLiLogger.kt
* LastUpdate 2026-02-06 08:27:44 * LastUpdate 2026-11-16 11:35:40
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -24,12 +24,22 @@ package com.mingliqiye.utils.logger
import org.slf4j.Logger import org.slf4j.Logger
import org.slf4j.Marker import org.slf4j.Marker
import org.slf4j.helpers.MessageFormatter
/**
* 简易 SLF4J Logger 实现,将各级别日志直接输出到标准输出流。
* 所有日志级别始终启用,消息格式遵循 SLF4J 的 {} 占位符风格。
*
* @param name 日志器名称,输出时作为标识显示
*/
class MingLiLogger(private val name: String) : Logger { class MingLiLogger(private val name: String) : Logger {
override fun getName(): String { override fun getName(): String {
return name return name
} }
/**
* 始终返回 true,TRACE 级别日志始终启用。
*/
override fun isTraceEnabled(): Boolean { override fun isTraceEnabled(): Boolean {
return true return true
} }
@@ -40,14 +50,14 @@ class MingLiLogger(private val name: String) : Logger {
override fun trace(format: String?, arg: Any?) { override fun trace(format: String?, arg: Any?) {
format?.let { format?.let {
val message = format1(it, arg) val message = format(it, arg)
toPrintln(message, MingLiLoggerLevel.TRACE) toPrintln(message, MingLiLoggerLevel.TRACE)
} }
} }
override fun trace(format: String?, arg1: Any?, arg2: Any?) { override fun trace(format: String?, arg1: Any?, arg2: Any?) {
format?.let { format?.let {
val message = format2(it, arg1, arg2) val message = format(it, arg1, arg2)
toPrintln(message, MingLiLoggerLevel.TRACE) toPrintln(message, MingLiLoggerLevel.TRACE)
} }
} }
@@ -66,6 +76,9 @@ class MingLiLogger(private val name: String) : Logger {
} }
} }
/**
* 始终返回 true,忽略 marker 参数。
*/
override fun isTraceEnabled(marker: Marker?): Boolean { override fun isTraceEnabled(marker: Marker?): Boolean {
return true return true
} }
@@ -90,6 +103,9 @@ class MingLiLogger(private val name: String) : Logger {
trace(msg, t) trace(msg, t)
} }
/**
* 始终返回 true,DEBUG 级别日志始终启用。
*/
override fun isDebugEnabled(): Boolean { override fun isDebugEnabled(): Boolean {
return true return true
} }
@@ -100,14 +116,14 @@ class MingLiLogger(private val name: String) : Logger {
override fun debug(format: String?, arg: Any?) { override fun debug(format: String?, arg: Any?) {
format?.let { format?.let {
val message = format1(it, arg) val message = format(it, arg)
toPrintln(message, MingLiLoggerLevel.DEBUG) toPrintln(message, MingLiLoggerLevel.DEBUG)
} }
} }
override fun debug(format: String?, arg1: Any?, arg2: Any?) { override fun debug(format: String?, arg1: Any?, arg2: Any?) {
format?.let { format?.let {
val message = format2(it, arg1, arg2) val message = format(it, arg1, arg2)
toPrintln(message, MingLiLoggerLevel.DEBUG) toPrintln(message, MingLiLoggerLevel.DEBUG)
} }
} }
@@ -126,6 +142,9 @@ class MingLiLogger(private val name: String) : Logger {
} }
} }
/**
* 始终返回 true,忽略 marker 参数。
*/
override fun isDebugEnabled(marker: Marker?): Boolean { override fun isDebugEnabled(marker: Marker?): Boolean {
return true return true
} }
@@ -150,6 +169,9 @@ class MingLiLogger(private val name: String) : Logger {
debug(msg, t) debug(msg, t)
} }
/**
* 始终返回 true,INFO 级别日志始终启用。
*/
override fun isInfoEnabled(): Boolean { override fun isInfoEnabled(): Boolean {
return true return true
} }
@@ -160,14 +182,14 @@ class MingLiLogger(private val name: String) : Logger {
override fun info(format: String?, arg: Any?) { override fun info(format: String?, arg: Any?) {
format?.let { format?.let {
val message = format1(it, arg) val message = format(it, arg)
toPrintln(message, MingLiLoggerLevel.INFO) toPrintln(message, MingLiLoggerLevel.INFO)
} }
} }
override fun info(format: String?, arg1: Any?, arg2: Any?) { override fun info(format: String?, arg1: Any?, arg2: Any?) {
format?.let { format?.let {
val message = format2(it, arg1, arg2) val message = format(it, arg1, arg2)
toPrintln(message, MingLiLoggerLevel.INFO) toPrintln(message, MingLiLoggerLevel.INFO)
} }
} }
@@ -186,6 +208,9 @@ class MingLiLogger(private val name: String) : Logger {
} }
} }
/**
* 始终返回 true,忽略 marker 参数。
*/
override fun isInfoEnabled(marker: Marker?): Boolean { override fun isInfoEnabled(marker: Marker?): Boolean {
return true return true
} }
@@ -210,6 +235,9 @@ class MingLiLogger(private val name: String) : Logger {
info(msg, t) info(msg, t)
} }
/**
* 始终返回 true,WARN 级别日志始终启用。
*/
override fun isWarnEnabled(): Boolean { override fun isWarnEnabled(): Boolean {
return true return true
} }
@@ -220,7 +248,7 @@ class MingLiLogger(private val name: String) : Logger {
override fun warn(format: String?, arg: Any?) { override fun warn(format: String?, arg: Any?) {
format?.let { format?.let {
val message = format1(it, arg) val message = format(it, arg)
toPrintln(message, MingLiLoggerLevel.WARN) toPrintln(message, MingLiLoggerLevel.WARN)
} }
} }
@@ -234,7 +262,7 @@ class MingLiLogger(private val name: String) : Logger {
override fun warn(format: String?, arg1: Any?, arg2: Any?) { override fun warn(format: String?, arg1: Any?, arg2: Any?) {
format?.let { format?.let {
val message = format2(it, arg1, arg2) val message = format(it, arg1, arg2)
toPrintln(message, MingLiLoggerLevel.WARN) toPrintln(message, MingLiLoggerLevel.WARN)
} }
} }
@@ -246,6 +274,9 @@ class MingLiLogger(private val name: String) : Logger {
} }
} }
/**
* 始终返回 true,忽略 marker 参数。
*/
override fun isWarnEnabled(marker: Marker?): Boolean { override fun isWarnEnabled(marker: Marker?): Boolean {
return true return true
} }
@@ -270,6 +301,9 @@ class MingLiLogger(private val name: String) : Logger {
warn(msg, t) warn(msg, t)
} }
/**
* 始终返回 true,ERROR 级别日志始终启用。
*/
override fun isErrorEnabled(): Boolean { override fun isErrorEnabled(): Boolean {
return true return true
} }
@@ -280,14 +314,14 @@ class MingLiLogger(private val name: String) : Logger {
override fun error(format: String?, arg: Any?) { override fun error(format: String?, arg: Any?) {
format?.let { format?.let {
val message = format1(it, arg) val message = format(it, arg)
toPrintln(message, MingLiLoggerLevel.ERROR) toPrintln(message, MingLiLoggerLevel.ERROR)
} }
} }
override fun error(format: String?, arg1: Any?, arg2: Any?) { override fun error(format: String?, arg1: Any?, arg2: Any?) {
format?.let { format?.let {
val message = format2(it, arg1, arg2) val message = format(it, arg1, arg2)
toPrintln(message, MingLiLoggerLevel.ERROR) toPrintln(message, MingLiLoggerLevel.ERROR)
} }
} }
@@ -299,12 +333,18 @@ class MingLiLogger(private val name: String) : Logger {
} }
} }
/**
* 输出 ERROR 级别日志,仅输出消息文本,忽略异常参数。
*/
override fun error(msg: String?, t: Throwable?) { override fun error(msg: String?, t: Throwable?) {
msg?.let { msg?.let {
toPrintln(it, MingLiLoggerLevel.ERROR) toPrintln(it, MingLiLoggerLevel.ERROR)
} }
} }
/**
* 始终返回 true,忽略 marker 参数。
*/
override fun isErrorEnabled(marker: Marker?): Boolean { override fun isErrorEnabled(marker: Marker?): Boolean {
return true return true
} }
@@ -329,6 +369,12 @@ class MingLiLogger(private val name: String) : Logger {
error(msg, t) error(msg, t)
} }
/**
* 按指定日志级别格式化并输出日志消息。
*
* @param message 日志消息内容
* @param level 日志级别
*/
fun toPrintln(message: String, level: MingLiLoggerLevel) { fun toPrintln(message: String, level: MingLiLoggerLevel) {
when (level) { when (level) {
MingLiLoggerLevel.TRACE -> wirteToSteam("[TRACE] [$name] $message\n") MingLiLoggerLevel.TRACE -> wirteToSteam("[TRACE] [$name] $message\n")
@@ -339,28 +385,23 @@ class MingLiLogger(private val name: String) : Logger {
} }
} }
/**
* 将字符串以字节形式写入标准输出流。
*
* @param string 要输出的字符串
*/
fun wirteToSteam(string: String) { fun wirteToSteam(string: String) {
System.out.write(string.toByteArray()) System.out.write(string.toByteArray())
} }
private fun format1(format: String, arg: Any?): String { private fun format(format: String, vararg args: Any?): String {
return if (format.contains("{}")) { return formatArray(format, args)
format.replaceFirst("{}", arg?.toString() ?: "null")
} else {
"$format $arg"
}
}
private fun format2(format: String, arg1: Any?, arg2: Any?): String {
return format.replaceFirst("{}", arg1?.toString() ?: "null")
.replaceFirst("{}", arg2?.toString() ?: "null")
} }
private fun formatArray(format: String, arguments: Array<out Any?>): String { private fun formatArray(format: String, arguments: Array<out Any?>): String {
var result = format return MessageFormatter.arrayFormat(
for (arg in arguments) { format,
result = result.replaceFirst("{}", arg?.toString() ?: "null") arguments
} ).message
return result
} }
} }
@@ -27,8 +27,15 @@ import org.slf4j.LoggerFactory
import java.lang.reflect.Method import java.lang.reflect.Method
import java.util.* import java.util.*
/**
* 日志器工厂,优先使用 SLF4J 实现(或 mingli-logger 的 Loggers)获取日志器,
* 在没有可用 SLF4J 实现时回退到内置的 MingLiLogger。
*/
class MingLiLoggerFactory { class MingLiLoggerFactory {
/**
* 伴生对象,提供获取日志器的静态方法。
*/
companion object { companion object {
private var nameMethod: Method? = null private var nameMethod: Method? = null
@@ -48,6 +55,12 @@ class MingLiLoggerFactory {
} }
/**
* 根据名称获取日志器。
*
* @param name 日志器名称
* @return 对应的 Logger 实例
*/
@JvmStatic @JvmStatic
fun getLogger(name: String): Logger { fun getLogger(name: String): Logger {
@@ -60,6 +73,12 @@ class MingLiLoggerFactory {
} else mingLiLoggerFactory.getLogger(name) } else mingLiLoggerFactory.getLogger(name)
} }
/**
* 根据类对象获取日志器,日志器名称为类的全限定名。
*
* @param clazz 用于命名日志器的类对象
* @return 对应的 Logger 实例
*/
@JvmStatic @JvmStatic
fun getLogger(clazz: Class<*>): Logger { fun getLogger(clazz: Class<*>): Logger {
return if (mingLiLoggerFactory.checkSLF4JImplementation()) { return if (mingLiLoggerFactory.checkSLF4JImplementation()) {
@@ -71,6 +90,12 @@ class MingLiLoggerFactory {
} else mingLiLoggerFactory.getLogger(clazz) } else mingLiLoggerFactory.getLogger(clazz)
} }
/**
* 通过 reified 类型参数获取日志器,日志器名称为类型 T 的全限定名。
*
* @param T 用于命名日志器的类型
* @return 对应的 Logger 实例
*/
inline fun <reified T> getLogger() = getLogger(T::class.java) inline fun <reified T> getLogger() = getLogger(T::class.java)
} }
@@ -22,10 +22,32 @@
package com.mingliqiye.utils.logger package com.mingliqiye.utils.logger
/**
* 日志级别枚举,定义 MingLiLogger 支持的五个日志级别。
*/
enum class MingLiLoggerLevel { enum class MingLiLoggerLevel {
/**
* 跟踪级别,最详细的调试信息
*/
TRACE, TRACE,
/**
* 调试级别
*/
DEBUG, DEBUG,
/**
* 信息级别
*/
INFO, INFO,
/**
* 警告级别
*/
WARN, WARN,
/**
* 错误级别
*/
ERROR ERROR
} }
@@ -28,6 +28,14 @@ import java.util.*
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
/**
* 使用键值对可变参数创建一个新的 HashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @param elements 键值对可变参数列表
* @return 新创建的 HashMap
*/
fun <K, V> newHashMap(vararg elements: Pair<K, V>): HashMap<K, V> { fun <K, V> newHashMap(vararg elements: Pair<K, V>): HashMap<K, V> {
val map = HashMap<K, V>() val map = HashMap<K, V>()
for (element in elements) { for (element in elements) {
@@ -36,14 +44,37 @@ fun <K, V> newHashMap(vararg elements: Pair<K, V>): HashMap<K, V> {
return map return map
} }
/**
* 创建一个指定初始容量的新 HashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @param size 初始容量大小
* @return 新创建的 HashMap
*/
fun <K, V> newHashMap(size: Int): HashMap<K, V> { fun <K, V> newHashMap(size: Int): HashMap<K, V> {
return HashMap(size) return HashMap(size)
} }
/**
* 创建一个新的 HashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @return 新创建的 HashMap
*/
fun <K, V> newHashMap(): HashMap<K, V> { fun <K, V> newHashMap(): HashMap<K, V> {
return HashMap() return HashMap()
} }
/**
* 使用 Map.Entry 可变参数创建一个新的 HashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @param elements 映射项可变参数列表
* @return 新创建的 HashMap
*/
fun <K, V> newHashMap(vararg elements: Map.Entry<K, V>): HashMap<K, V> { fun <K, V> newHashMap(vararg elements: Map.Entry<K, V>): HashMap<K, V> {
val map = HashMap<K, V>() val map = HashMap<K, V>()
for (element in elements) { for (element in elements) {
@@ -52,6 +83,14 @@ fun <K, V> newHashMap(vararg elements: Map.Entry<K, V>): HashMap<K, V> {
return map return map
} }
/**
* 使用 Map.Entry 可变参数创建一个新的 ConcurrentHashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @param elements 映射项可变参数列表
* @return 新创建的 ConcurrentHashMap
*/
fun <K, V> newConcurrentHashMap(vararg elements: Map.Entry<K, V>): ConcurrentHashMap<K, V> { fun <K, V> newConcurrentHashMap(vararg elements: Map.Entry<K, V>): ConcurrentHashMap<K, V> {
val map = newConcurrentHashMap<K, V>() val map = newConcurrentHashMap<K, V>()
for (element in elements) { for (element in elements) {
@@ -60,6 +99,14 @@ fun <K, V> newConcurrentHashMap(vararg elements: Map.Entry<K, V>): ConcurrentHas
return map return map
} }
/**
* 使用 Map.Entry 可变参数创建一个新的 LinkedHashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @param elements 映射项可变参数列表
* @return 新创建的 LinkedHashMap
*/
fun <K, V> newLinkedHashMap(vararg elements: Map.Entry<K, V>): LinkedHashMap<K, V> { fun <K, V> newLinkedHashMap(vararg elements: Map.Entry<K, V>): LinkedHashMap<K, V> {
val map = newLinkedHashMap<K, V>() val map = newLinkedHashMap<K, V>()
for (element in elements) { for (element in elements) {
@@ -68,6 +115,14 @@ fun <K, V> newLinkedHashMap(vararg elements: Map.Entry<K, V>): LinkedHashMap<K,
return map return map
} }
/**
* 使用 Map.Entry 可变参数创建一个新的 Hashtable 实例。
*
* @param K 键类型
* @param V 值类型
* @param elements 映射项可变参数列表
* @return 新创建的 Hashtable
*/
fun <K, V> newHashtable(vararg elements: Map.Entry<K, V>): Hashtable<K, V> { fun <K, V> newHashtable(vararg elements: Map.Entry<K, V>): Hashtable<K, V> {
val map = newHashtable<K, V>() val map = newHashtable<K, V>()
for (element in elements) { for (element in elements) {
@@ -76,6 +131,14 @@ fun <K, V> newHashtable(vararg elements: Map.Entry<K, V>): Hashtable<K, V> {
return map return map
} }
/**
* 使用 Map.Entry 可变参数创建一个新的 TreeMap 实例。
*
* @param K 键类型,必须实现 Comparable 接口
* @param V 值类型
* @param elements 映射项可变参数列表
* @return 新创建的 TreeMap
*/
fun <K : Comparable<K>, V> newTreeMap(vararg elements: Map.Entry<K, V>): TreeMap<K, V> { fun <K : Comparable<K>, V> newTreeMap(vararg elements: Map.Entry<K, V>): TreeMap<K, V> {
val map = newTreeMap<K, V>() val map = newTreeMap<K, V>()
for (element in elements) { for (element in elements) {
@@ -84,18 +147,48 @@ fun <K : Comparable<K>, V> newTreeMap(vararg elements: Map.Entry<K, V>): TreeMap
return map return map
} }
/**
* 将当前 Map 转换为新的 HashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @return 新创建的 HashMap
*/
inline fun <reified K, reified V> Map<K, V>.newHashMap(): HashMap<K, V> { inline fun <reified K, reified V> Map<K, V>.newHashMap(): HashMap<K, V> {
return HashMap(this) return HashMap(this)
} }
/**
* 创建一个新的 LinkedHashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @return 新创建的 LinkedHashMap
*/
fun <K, V> newLinkedHashMap(): LinkedHashMap<K, V> { fun <K, V> newLinkedHashMap(): LinkedHashMap<K, V> {
return LinkedHashMap() return LinkedHashMap()
} }
/**
* 创建一个指定初始容量的新 LinkedHashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @param size 初始容量大小
* @return 新创建的 LinkedHashMap
*/
fun <K, V> newLinkedHashMap(size: Int): LinkedHashMap<K, V> { fun <K, V> newLinkedHashMap(size: Int): LinkedHashMap<K, V> {
return LinkedHashMap(size) return LinkedHashMap(size)
} }
/**
* 使用键值对可变参数创建一个新的 LinkedHashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @param elements 键值对可变参数列表
* @return 新创建的 LinkedHashMap
*/
fun <K, V> newLinkedHashMap(vararg elements: Pair<K, V>): LinkedHashMap<K, V> { fun <K, V> newLinkedHashMap(vararg elements: Pair<K, V>): LinkedHashMap<K, V> {
val map = newLinkedHashMap<K, V>() val map = newLinkedHashMap<K, V>()
for (element in elements) { for (element in elements) {
@@ -104,14 +197,36 @@ fun <K, V> newLinkedHashMap(vararg elements: Pair<K, V>): LinkedHashMap<K, V> {
return map return map
} }
/**
* 将当前 Map 转换为新的 LinkedHashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @return 新创建的 LinkedHashMap
*/
inline fun <reified K, reified V> Map<K, V>.newLinkedHashMap(): LinkedHashMap<K, V> { inline fun <reified K, reified V> Map<K, V>.newLinkedHashMap(): LinkedHashMap<K, V> {
return LinkedHashMap(this) return LinkedHashMap(this)
} }
/**
* 创建一个新的 TreeMap 实例。
*
* @param K 键类型,必须实现 Comparable 接口
* @param V 值类型
* @return 新创建的 TreeMap
*/
fun <K : Comparable<K>, V> newTreeMap(): TreeMap<K, V> { fun <K : Comparable<K>, V> newTreeMap(): TreeMap<K, V> {
return TreeMap() return TreeMap()
} }
/**
* 使用键值对可变参数创建一个新的 TreeMap 实例。
*
* @param K 键类型,必须实现 Comparable 接口
* @param V 值类型
* @param elements 键值对可变参数列表
* @return 新创建的 TreeMap
*/
fun <K : Comparable<K>, V> newTreeMap(vararg elements: Pair<K, V>): TreeMap<K, V> { fun <K : Comparable<K>, V> newTreeMap(vararg elements: Pair<K, V>): TreeMap<K, V> {
val map = newTreeMap<K, V>() val map = newTreeMap<K, V>()
for (element in elements) { for (element in elements) {
@@ -120,18 +235,48 @@ fun <K : Comparable<K>, V> newTreeMap(vararg elements: Pair<K, V>): TreeMap<K, V
return map return map
} }
/**
* 将当前 Map 转换为新的 TreeMap 实例。
*
* @param K 键类型,必须实现 Comparable 接口
* @param V 值类型
* @return 新创建的 TreeMap
*/
inline fun <reified K : Comparable<K>, reified V> Map<K, V>.newTreeMap(): TreeMap<K, V> { inline fun <reified K : Comparable<K>, reified V> Map<K, V>.newTreeMap(): TreeMap<K, V> {
return TreeMap(this) return TreeMap(this)
} }
/**
* 创建一个新的 Hashtable 实例。
*
* @param K 键类型
* @param V 值类型
* @return 新创建的 Hashtable
*/
fun <K, V> newHashtable(): Hashtable<K, V> { fun <K, V> newHashtable(): Hashtable<K, V> {
return Hashtable() return Hashtable()
} }
/**
* 创建一个指定初始容量的新 Hashtable 实例。
*
* @param K 键类型
* @param V 值类型
* @param size 初始容量大小
* @return 新创建的 Hashtable
*/
fun <K, V> newHashtable(size: Int): Hashtable<K, V> { fun <K, V> newHashtable(size: Int): Hashtable<K, V> {
return Hashtable(size) return Hashtable(size)
} }
/**
* 使用键值对可变参数创建一个新的 Hashtable 实例。
*
* @param K 键类型
* @param V 值类型
* @param elements 键值对可变参数列表
* @return 新创建的 Hashtable
*/
fun <K, V> newHashtable(vararg elements: Pair<K, V>): Hashtable<K, V> { fun <K, V> newHashtable(vararg elements: Pair<K, V>): Hashtable<K, V> {
val map = newHashtable<K, V>() val map = newHashtable<K, V>()
for (element in elements) { for (element in elements) {
@@ -140,20 +285,50 @@ fun <K, V> newHashtable(vararg elements: Pair<K, V>): Hashtable<K, V> {
return map return map
} }
/**
* 将当前 Map 转换为新的 Hashtable 实例。
*
* @param K 键类型
* @param V 值类型
* @return 新创建的 Hashtable
*/
inline fun <reified K, reified V> Map<K, V>.newHashtable(): Hashtable<K, V> { inline fun <reified K, reified V> Map<K, V>.newHashtable(): Hashtable<K, V> {
val hashtable = Hashtable<K, V>() val hashtable = Hashtable<K, V>()
hashtable.putAll(this) hashtable.putAll(this)
return hashtable return hashtable
} }
/**
* 创建一个新的 ConcurrentHashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @return 新创建的 ConcurrentHashMap
*/
fun <K, V> newConcurrentHashMap(): ConcurrentHashMap<K, V> { fun <K, V> newConcurrentHashMap(): ConcurrentHashMap<K, V> {
return ConcurrentHashMap() return ConcurrentHashMap()
} }
/**
* 创建一个指定初始容量的新 ConcurrentHashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @param size 初始容量大小
* @return 新创建的 ConcurrentHashMap
*/
fun <K, V> newConcurrentHashMap(size: Int): ConcurrentHashMap<K, V> { fun <K, V> newConcurrentHashMap(size: Int): ConcurrentHashMap<K, V> {
return ConcurrentHashMap(size) return ConcurrentHashMap(size)
} }
/**
* 使用键值对可变参数创建一个新的 ConcurrentHashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @param elements 键值对可变参数列表
* @return 新创建的 ConcurrentHashMap
*/
fun <K, V> newConcurrentHashMap(vararg elements: Pair<K, V>): ConcurrentHashMap<K, V> { fun <K, V> newConcurrentHashMap(vararg elements: Pair<K, V>): ConcurrentHashMap<K, V> {
val map = newConcurrentHashMap<K, V>() val map = newConcurrentHashMap<K, V>()
for (element in elements) { for (element in elements) {
@@ -162,10 +337,25 @@ fun <K, V> newConcurrentHashMap(vararg elements: Pair<K, V>): ConcurrentHashMap<
return map return map
} }
/**
* 将当前 Map 转换为新的 ConcurrentHashMap 实例。
*
* @param K 键类型
* @param V 值类型
* @return 新创建的 ConcurrentHashMap
*/
inline fun <reified K, reified V> Map<K, V>.newConcurrentHashMap(): ConcurrentHashMap<K, V> { inline fun <reified K, reified V> Map<K, V>.newConcurrentHashMap(): ConcurrentHashMap<K, V> {
return ConcurrentHashMap(this) return ConcurrentHashMap(this)
} }
/**
* 将映射项列表转换为 Map。
*
* @param K 键类型
* @param V 值类型
* @param entries 映射项列表
* @return 由映射项组成的 Map
*/
fun <K, V> ofEntries(entries: List<MutableMap.MutableEntry<K, V>>): Map<K, V> { fun <K, V> ofEntries(entries: List<MutableMap.MutableEntry<K, V>>): Map<K, V> {
return entries.associate { it.key to it.value } return entries.associate { it.key to it.value }
} }
@@ -26,8 +26,18 @@ package com.mingliqiye.utils.metadata
import com.mingliqiye.utils.resource.ResourceUtils import com.mingliqiye.utils.resource.ResourceUtils
import java.util.stream.Collectors.toMap import java.util.stream.Collectors.toMap
/**
* 元数据资源定位锚点类,仅用于定位 `/META-INF/meta-data` 资源所在的类加载器
*/
class MetaDataResource class MetaDataResource
/**
* 读取并解析 `/META-INF/meta-data` 资源文件
*
* 文件内容按行解析为 `key=value` 形式的键值对,空行与格式不合法的行会被忽略。
*
* @return 元数据键值对映射
*/
fun getMetaData(): Map<String, String> { fun getMetaData(): Map<String, String> {
return ResourceUtils.getResourceAsString<MetaDataResource>("/META-INF/meta-data").split("\n").stream().map { return ResourceUtils.getResourceAsString<MetaDataResource>("/META-INF/meta-data").split("\n").stream().map {
if (it.isBlank()) { if (it.isBlank()) {
@@ -42,6 +52,11 @@ fun getMetaData(): Map<String, String> {
}.filter { it != null }.collect(toMap({ it!!.first }, { it!!.second })) }.filter { it != null }.collect(toMap({ it!!.first }, { it!!.second }))
} }
/**
* mingli-utils 库的构建元数据,延迟初始化
*
* 从 `/META-INF/meta-data` 资源解析并填充 [MingliUtilsMetaData],缺失的字段以空字符串代替。
*/
val mingliUtilsMetaData: MingliUtilsMetaData by lazy { val mingliUtilsMetaData: MingliUtilsMetaData by lazy {
val metaData = getMetaData() val metaData = getMetaData()
MingliUtilsMetaData().apply { MingliUtilsMetaData().apply {

Some files were not shown because too many files have changed in this diff Show More