Compare commits
29
Commits
85fd391849
...
5.5.5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae41240806
|
||
|
|
cb7fdb4f19
|
||
|
|
3d1896bd64
|
||
|
|
0e0d2b03cc
|
||
|
|
2e54e3d651
|
||
|
|
528802d881
|
||
|
|
487f956f4f
|
||
|
|
64e3af50ed
|
||
|
|
7760201639
|
||
|
|
713342bbc6
|
||
|
|
988a0c0dc1
|
||
|
|
44ea9b114d
|
||
|
|
3bacf90940
|
||
|
|
28a2987dc3
|
||
|
|
8069de37f2
|
||
|
|
51eb838a36
|
||
|
|
d0887ea1f7
|
||
|
|
16da482de7
|
||
|
|
aa83f575b1
|
||
|
|
510ff69e2c
|
||
|
|
184db461d7
|
||
|
|
535c03d14a
|
||
|
|
5714aef444
|
||
|
|
7a3bc01b11
|
||
|
|
792ddf0255
|
||
|
|
f4025cbad9 | ||
|
|
eaf7ee7a31 | ||
|
|
38ad9884d0 | ||
|
|
0e5ce5597b |
@@ -0,0 +1,92 @@
|
||||
# Changelog
|
||||
|
||||

|
||||
|
||||
本文件记录 mingli-utils 各版本的主要变更。
|
||||
|
||||
## [5.5.4] - 2026-11-18
|
||||
|
||||
### 新增
|
||||
|
||||
- **hash**:新增 `HashCodec` 哈希编解码器接口——实现类只需重写 `hash(InputStream)` 一个方法,
|
||||
字节数组/字符串/文件/路径重载、十六进制输出(`hashHex`)与基于 `MessageDigest.isEqual`
|
||||
的常量时间校验(`verifyHash`)均由默认实现提供;新增 `MessageDigestCodec` 流式基类
|
||||
(8KB 缓冲、恒定内存、不关闭调用方流)及 13 种 JDK 标准算法实现
|
||||
(MD2、MD5、SHA-1、SHA-224/256/384/512、SHA-512/224、SHA-512/256、SHA3-224/256/384/512);
|
||||
提供 `HashUtils` 懒加载单例(`MD2`~`SHA512256`)与 `HashType` 枚举;
|
||||
新增 `TestHash` 测试覆盖已知向量、全部算法一致性、流生命周期与文件/路径重载。
|
||||
- **test**:新增非官方 Log4j2 配置 XSD(覆盖 21 种 Appender、13 种 Layout、11 种 Filter、
|
||||
滚动策略与清理条件等,未知插件元素以开放内容模型放行),`log4j2.xml` 接入 Schema 校验。
|
||||
|
||||
### 变更
|
||||
|
||||
- **springboot**:事件监听注解迁移为 Java 实现——新增 `ApplicationReadyEventListener`、
|
||||
`ContextClosedEventListener`;`ApplicationStartedRunner`、`ApplicationDestroyedRunner`
|
||||
标记为废弃;移除 Kotlin 版注解及 `ApplicationListener`、`ApplicationRunnerData`;
|
||||
`Okhttp3AutoConfiguration` 改用 `@ContextClosedEventListener`。
|
||||
- **http**:`MediaType` 枚举项之间补充空行(纯格式化,无内容变更)。
|
||||
|
||||
### 修复
|
||||
|
||||
- **build**:修正 `signing.secretKeyRingFile` 属性名笔误(误插入空格)。
|
||||
|
||||
### 文档
|
||||
|
||||
- hash 包全部接口、类、枚举与懒加载单例补全中文 KDoc;
|
||||
4 个 Spring Boot 事件监听注解补全 Javadoc。
|
||||
|
||||
## [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 缩进并补全尾随逗号。
|
||||
+41
-15
@@ -16,13 +16,37 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils
|
||||
* CurrentFile build.gradle.kts
|
||||
* LastUpdate 2026-10-11 16:44:37
|
||||
* LastUpdate 2026-11-18 08:42:41
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
/*
|
||||
* 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 {
|
||||
idea
|
||||
java
|
||||
@@ -61,7 +85,8 @@ kotlin {
|
||||
repositories {
|
||||
mavenLocal()
|
||||
maven {
|
||||
url = uri("https://maven.mingliqiye.com/")
|
||||
name = "mingliqiye-public"
|
||||
url = uri("https://repository.mingliqiye.com/repository/maven-public/")
|
||||
}
|
||||
mavenCentral()
|
||||
}
|
||||
@@ -84,6 +109,8 @@ dependencies {
|
||||
compileOnly("net.java.dev.jna:jna:5.17.0")
|
||||
compileOnly("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.8")
|
||||
compileOnly("com.baomidou:mybatis-plus-extension:3.5.15")
|
||||
compileOnly("com.baomidou:mybatis-plus-jsqlparser:3.5.15")
|
||||
compileOnly("com.baomidou:mybatis-plus-spring:3.5.9")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.7.1")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
testImplementation("com.mingliqiye.logger:logger-log4j2:1.0.9")
|
||||
@@ -158,32 +185,31 @@ tasks.withType<org.gradle.jvm.tasks.Jar> {
|
||||
}
|
||||
val isJdk8Build = project.findProperty("buildForJdk8") == "true"
|
||||
|
||||
|
||||
dokka {
|
||||
pluginsConfiguration.html {
|
||||
customAssets.from("logo.png")
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register<Jar>("javaDocJar") {
|
||||
group = "build"
|
||||
archiveClassifier.set("javadoc-dec")
|
||||
dependsOn("dokkaGeneratePublicationJavadoc")
|
||||
archiveClassifier.set("javadoc")
|
||||
dependsOn("dokkaGenerateJavadoc")
|
||||
from(buildDir.resolve("dokka/javadoc"))
|
||||
}
|
||||
|
||||
tasks.register<Jar>("kotlinDocJar") {
|
||||
group = "build"
|
||||
archiveClassifier.set("javadoc")
|
||||
archiveClassifier.set("kotlindoc")
|
||||
dependsOn("dokkaGeneratePublicationHtml")
|
||||
from(buildDir.resolve("dokka/html"))
|
||||
}
|
||||
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 {
|
||||
create<MavenPublication>("mavenJava") {
|
||||
from(components["java"])
|
||||
artifact(tasks.named("javaDocJar"))
|
||||
artifact(tasks.named("kotlinDocJar"))
|
||||
artifactId = ARTIFACTID
|
||||
pom {
|
||||
|
||||
+2
-2
@@ -16,10 +16,10 @@
|
||||
# ProjectName mingli-utils
|
||||
# ModuleName mingli-utils
|
||||
# CurrentFile gradle.properties
|
||||
# LastUpdate 2026-10-22 20:26:20
|
||||
# LastUpdate 2026-11-18 19:46:50
|
||||
# UpdateUser MingLiPro
|
||||
#
|
||||
JDKVERSIONS=17
|
||||
GROUPSID=com.mingliqiye.utils
|
||||
ARTIFACTID=mingli-utils
|
||||
VERSIONS=5.3.4
|
||||
VERSIONS=5.5.5
|
||||
|
||||
Binary file not shown.
@@ -26,7 +26,16 @@ import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.cfg.MapperBuilder;
|
||||
|
||||
|
||||
/**
|
||||
* Jackson 3 API 的 Java 辅助类,用于在 Java 侧调用 Kotlin 内联/受限 API。
|
||||
*/
|
||||
public class Jackson3ApiJavaHelper {
|
||||
/**
|
||||
* 基于现有 ObjectMapper 创建可重新配置的 MapperBuilder。
|
||||
*
|
||||
* @param objectMapper 需要重建的 ObjectMapper 实例
|
||||
* @return 由该 ObjectMapper 派生的 MapperBuilder
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
static MapperBuilder rebuild(ObjectMapper objectMapper) {
|
||||
return objectMapper.rebuild();
|
||||
|
||||
@@ -29,7 +29,13 @@ import java.net.InetAddress;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* 工具库入口类,提供启动 Banner 打印以及进程、主机、用户等基础信息的获取方法。
|
||||
*/
|
||||
public class Main {
|
||||
/**
|
||||
* 启动时打印的 ASCII 艺术 Banner 文本
|
||||
*/
|
||||
public final static String BANNER =
|
||||
"| $$\\ $$\\ $$\\ $$\\ $$\\ $$$$$$$$\\ $$$$$$\\ \n" +
|
||||
"| $$$\\ $$$ |$$ | $$ | $$ |\\__$$ __|$$ __$$\\ \n" +
|
||||
@@ -40,6 +46,11 @@ public class Main {
|
||||
"| $$ | \\_/ $$ |$$$$$$$$\\\\$$$$$$ | $$ | \\$$$$$$ \n" +
|
||||
"| \\__| \\__|\\________|\\______/ \\__| \\______/ \n|\n";
|
||||
|
||||
/**
|
||||
* 程序入口,打印 Banner 与构建元数据信息,打印失败时静默忽略。
|
||||
*
|
||||
* @param args 命令行参数(未使用)
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
printb();
|
||||
@@ -47,6 +58,11 @@ public class Main {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前进程 PID 字符串。
|
||||
*
|
||||
* @return 当前进程 PID;获取失败时返回 "-1"
|
||||
*/
|
||||
public static String getPid() {
|
||||
try {
|
||||
var name = ManagementFactory.getRuntimeMXBean().getName();
|
||||
@@ -61,6 +77,11 @@ public class Main {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取计算机名,依次尝试环境变量 COMPUTERNAME、HOSTNAME 与本机主机名。
|
||||
*
|
||||
* @return 计算机名;获取失败时返回 "unknown"
|
||||
*/
|
||||
public static String getComputerName() {
|
||||
try {
|
||||
var name = System.getenv("COMPUTERNAME");
|
||||
@@ -76,6 +97,11 @@ public class Main {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户名,依次尝试环境变量 USERNAME、USER 与 user.name。
|
||||
*
|
||||
* @return 当前用户名;获取失败时返回 "unknown"
|
||||
*/
|
||||
public static String getUserName() {
|
||||
try {
|
||||
String user = System.getenv("USERNAME");
|
||||
@@ -96,6 +122,12 @@ public class Main {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 打印 Banner 及构建元数据、JDK 版本、PID、计算机名、用户名与当前时间。
|
||||
* 若元数据资源不存在则直接返回。
|
||||
*
|
||||
* @throws IOException 读取元数据资源失败时抛出
|
||||
*/
|
||||
public static void printb() throws IOException {
|
||||
InputStream inputStream = Main.class.getResourceAsStream("/META-INF/meta-data");
|
||||
if (inputStream == null) return;
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* 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 ApplicationDestroyedRunner.java
|
||||
* LastUpdate 2026-11-18 08:21:37
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.springboot.annotation;
|
||||
|
||||
import org.springframework.context.event.ContextClosedEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.AliasFor;
|
||||
import org.springframework.core.annotation.Order;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 应用销毁(上下文关闭)事件监听注解。
|
||||
*
|
||||
* <p>标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
|
||||
* ({@link ContextClosedEvent} 发布)时自动调用该方法。</p>
|
||||
*
|
||||
* @deprecated 已弃用,请改用 {@link ContextClosedEventListener}(监听相同事件,命名更规范)。
|
||||
* @see ContextClosedEventListener
|
||||
* @see EventListener
|
||||
* @see ContextClosedEvent
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@EventListener(ContextClosedEvent.class)
|
||||
@Order
|
||||
@Deprecated(since = "use ApplicationReadyEventListener")
|
||||
public @interface ApplicationDestroyedRunner {
|
||||
/**
|
||||
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||
*
|
||||
* @return 条件表达式,默认为空字符串(无条件执行)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "condition")
|
||||
String condition() default "";
|
||||
|
||||
/**
|
||||
* 当事件不是 {@link ContextClosedEvent} 类型时是否仍默认执行监听方法。
|
||||
*
|
||||
* @return 是否默认执行,默认为 true
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
|
||||
boolean defaultExecution() default true;
|
||||
|
||||
/**
|
||||
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||
*
|
||||
* @return 监听器 id,默认为空字符串(自动生成)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "id")
|
||||
String id() default "";
|
||||
|
||||
/**
|
||||
* 监听器的执行顺序,值越小优先级越高。
|
||||
*
|
||||
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
|
||||
* @see Ordered#getOrder()
|
||||
*/
|
||||
@AliasFor(annotation = Order.class, attribute = "value")
|
||||
int order() default Ordered.LOWEST_PRECEDENCE;
|
||||
}
|
||||
+95
@@ -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 ApplicationReadyEventListener.java
|
||||
* LastUpdate 2026-11-18 08:21:57
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.springboot.annotation;
|
||||
|
||||
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.AliasFor;
|
||||
import org.springframework.core.annotation.Order;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
|
||||
/**
|
||||
* 应用就绪事件监听注解。
|
||||
*
|
||||
* <p>标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
|
||||
* ({@link ApplicationReadyEvent} 发布)时自动调用该方法,
|
||||
* 等价于 {@code @EventListener(ApplicationReadyEvent.class)} 的组合简化写法。</p>
|
||||
*
|
||||
* <p>使用示例:</p>
|
||||
* <pre>{@code
|
||||
* @Component
|
||||
* public class InitTask {
|
||||
* @ApplicationReadyEventListener(order = 0)
|
||||
* public void onReady() {
|
||||
* // 应用就绪后执行的初始化逻辑
|
||||
* }
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* @see EventListener
|
||||
* @see ApplicationReadyEvent
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Order
|
||||
public @interface ApplicationReadyEventListener {
|
||||
/**
|
||||
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||
*
|
||||
* @return 条件表达式,默认为空字符串(无条件执行)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "condition")
|
||||
String condition() default "";
|
||||
|
||||
/**
|
||||
* 当事件不是 {@link ApplicationReadyEvent} 类型时是否仍默认执行监听方法。
|
||||
*
|
||||
* @return 是否默认执行,默认为 true
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
|
||||
boolean defaultExecution() default true;
|
||||
|
||||
/**
|
||||
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||
*
|
||||
* @return 监听器 id,默认为空字符串(自动生成)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "id")
|
||||
String id() default "";
|
||||
|
||||
|
||||
/**
|
||||
* 监听器的执行顺序,值越小优先级越高。
|
||||
*
|
||||
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
|
||||
* @see Ordered#getOrder()
|
||||
*/
|
||||
@AliasFor(annotation = Order.class, attribute = "value")
|
||||
int order() default Ordered.LOWEST_PRECEDENCE;
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* 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 ApplicationStartedRunner.java
|
||||
* LastUpdate 2026-11-18 08:21:57
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.springboot.annotation;
|
||||
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.AliasFor;
|
||||
import org.springframework.core.annotation.Order;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 应用启动完成事件监听注解。
|
||||
*
|
||||
* <p>标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
|
||||
* ({@link ApplicationReadyEvent} 发布)时自动调用该方法。</p>
|
||||
*
|
||||
* @deprecated 已弃用,请改用 {@link ApplicationReadyEventListener}(功能完全一致,命名更规范)。
|
||||
* @see ApplicationReadyEventListener
|
||||
* @see EventListener
|
||||
* @see ApplicationReadyEvent
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Order
|
||||
@Deprecated(since = "use ApplicationReadyEventListener")
|
||||
public @interface ApplicationStartedRunner {
|
||||
/**
|
||||
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||
*
|
||||
* @return 条件表达式,默认为空字符串(无条件执行)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "condition")
|
||||
String condition() default "";
|
||||
|
||||
/**
|
||||
* 当事件不是 {@link ApplicationReadyEvent} 类型时是否仍默认执行监听方法。
|
||||
*
|
||||
* @return 是否默认执行,默认为 true
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
|
||||
boolean defaultExecution() default true;
|
||||
|
||||
/**
|
||||
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||
*
|
||||
* @return 监听器 id,默认为空字符串(自动生成)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "id")
|
||||
String id() default "";
|
||||
|
||||
|
||||
/**
|
||||
* 监听器的执行顺序,值越小优先级越高。
|
||||
*
|
||||
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
|
||||
* @see Ordered#getOrder()
|
||||
*/
|
||||
@AliasFor(annotation = Order.class, attribute = "value")
|
||||
int order() default Ordered.LOWEST_PRECEDENCE;
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* 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 ContextClosedEventListener.java
|
||||
* LastUpdate 2026-11-18 08:21:23
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.springboot.annotation;
|
||||
|
||||
import org.springframework.context.event.ContextClosedEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.AliasFor;
|
||||
import org.springframework.core.annotation.Order;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 应用上下文关闭事件监听注解。
|
||||
*
|
||||
* <p>标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
|
||||
* ({@link ContextClosedEvent} 发布)时自动调用该方法,
|
||||
* 等价于 {@code @EventListener(ContextClosedEvent.class)} 的组合简化写法,
|
||||
* 适用于应用停机前的资源清理、状态保存等场景。</p>
|
||||
*
|
||||
* <p>使用示例:</p>
|
||||
* <pre>{@code
|
||||
* @Component
|
||||
* public class CleanupTask {
|
||||
* @ContextClosedEventListener
|
||||
* public void onClosed() {
|
||||
* // 上下文关闭前执行的清理逻辑
|
||||
* }
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* @see EventListener
|
||||
* @see ContextClosedEvent
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@EventListener(ContextClosedEvent.class)
|
||||
@Order
|
||||
public @interface ContextClosedEventListener {
|
||||
/**
|
||||
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||
*
|
||||
* @return 条件表达式,默认为空字符串(无条件执行)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "condition")
|
||||
String condition() default "";
|
||||
|
||||
/**
|
||||
* 当事件不是 {@link ContextClosedEvent} 类型时是否仍默认执行监听方法。
|
||||
*
|
||||
* @return 是否默认执行,默认为 true
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
|
||||
boolean defaultExecution() default true;
|
||||
|
||||
/**
|
||||
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||
*
|
||||
* @return 监听器 id,默认为空字符串(自动生成)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "id")
|
||||
String id() default "";
|
||||
|
||||
/**
|
||||
* 监听器的执行顺序,值越小优先级越高。
|
||||
*
|
||||
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
|
||||
* @see Ordered#getOrder()
|
||||
*/
|
||||
@AliasFor(annotation = Order.class, attribute = "value")
|
||||
int order() default Ordered.LOWEST_PRECEDENCE;
|
||||
}
|
||||
@@ -13,10 +13,10 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
* ProjectName mingli-utils
|
||||
* ProjectName FastBaseMapper.kt
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile SuperStream.java
|
||||
* LastUpdate 2026-10-11 17:23:57
|
||||
* LastUpdate 2026-10-26 23:22:18
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
|
||||
@@ -34,10 +34,15 @@ import javax.crypto.Cipher
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/** 加密算法名称:AES。 */
|
||||
const val ALGORITHM = "AES"
|
||||
/** AES 加密变换模式:GCM 模式,无填充。 */
|
||||
const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||
/** GCM 模式初始化向量(IV)长度,单位字节。 */
|
||||
const val GCM_IV_LENGTH = 12
|
||||
/** GCM 模式认证标签(Tag)长度,单位字节。 */
|
||||
const val GCM_TAG_LENGTH = 16
|
||||
/** 全局安全随机数生成器,用于生成加密安全的随机 IV。 */
|
||||
val SECURE_RANDOM = SecureRandom()
|
||||
|
||||
|
||||
|
||||
@@ -37,5 +37,5 @@ import kotlin.reflect.KClass
|
||||
@Target(AnnotationTarget.CLASS)
|
||||
@Retention(AnnotationRetention.SOURCE)
|
||||
annotation class AutoService(
|
||||
val value: Array<KClass<*>> = []
|
||||
val value: Array<KClass<*>> = [],
|
||||
)
|
||||
|
||||
@@ -34,5 +34,5 @@ import com.mingliqiye.utils.uuid.UUIDFormatType
|
||||
@Target(AnnotationTarget.FIELD)
|
||||
annotation class UUIDJsonFormat(
|
||||
val value: UUIDFormatType = UUIDFormatType.NO_UPPER_SPACE,
|
||||
val base: BaseType = BaseType.BASE16
|
||||
val base: BaseType = BaseType.BASE16,
|
||||
)
|
||||
|
||||
@@ -33,12 +33,26 @@ import javax.lang.model.type.TypeMirror
|
||||
import javax.tools.StandardLocation
|
||||
|
||||
|
||||
/**
|
||||
* [AutoService] 注解的编译期处理器。
|
||||
*
|
||||
* 扫描标注了 [AutoService] 的类,收集服务接口与实现类的映射关系,
|
||||
* 并在编译输出目录的 META-INF/services 下生成对应的服务注册文件。
|
||||
*/
|
||||
@SupportedAnnotationTypes("com.mingliqiye.utils.annotation.AutoService")
|
||||
class AutoServiceProcessor : AbstractProcessor() {
|
||||
override fun init(processingEnv: ProcessingEnvironment) {
|
||||
super.init(processingEnv)
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理标注了 [AutoService] 的元素,收集服务接口与实现类的映射并生成服务注册文件。
|
||||
* 若注解未显式指定服务接口,则默认使用该类直接实现的接口。
|
||||
*
|
||||
* @param annotations 本轮处理的注解类型集合
|
||||
* @param roundEnv 当前轮次的处理环境
|
||||
* @return 是否已处理该注解,存在标注元素时返回 true,否则返回 false
|
||||
*/
|
||||
override fun process(
|
||||
annotations: Set<TypeElement>,
|
||||
roundEnv: RoundEnvironment,
|
||||
@@ -73,6 +87,12 @@ class AutoServiceProcessor : AbstractProcessor() {
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据服务接口与实现类的映射,在 META-INF/services 目录下生成服务注册文件。
|
||||
* 实现列表为空或文件创建失败时打印提示信息并跳过。
|
||||
*
|
||||
* @param map 服务接口全限定名到实现类全限定名列表的映射
|
||||
*/
|
||||
fun processClassAnnotation(map: Map<String, MutableList<String>>) {
|
||||
map.forEach { (interfaceName, implementations) ->
|
||||
if (implementations.isEmpty()) {
|
||||
|
||||
@@ -24,6 +24,11 @@ package com.mingliqiye.utils.base
|
||||
|
||||
import java.math.BigInteger
|
||||
|
||||
/**
|
||||
* Base10 编解码器实现类。
|
||||
*
|
||||
* 提供字节数组与十进制字符串之间的相互转换功能,基于 [BigInteger] 实现。
|
||||
*/
|
||||
internal class Base10Codec : BaseCodec {
|
||||
|
||||
/**
|
||||
|
||||
@@ -32,7 +32,13 @@ package com.mingliqiye.utils.base
|
||||
*/
|
||||
internal class Base256Codec : BaseCodec {
|
||||
|
||||
/**
|
||||
* 伴生对象,持有 Base256 的编码字符集及其反向索引表。
|
||||
*/
|
||||
companion object {
|
||||
/**
|
||||
* Base256 编码字符集,共 256 个字符,数组索引即对应的字节值(0~255)。
|
||||
*/
|
||||
val code = arrayOf(
|
||||
'!',
|
||||
'#',
|
||||
@@ -291,6 +297,9 @@ internal class Base256Codec : BaseCodec {
|
||||
'▘',
|
||||
'▙'
|
||||
)
|
||||
/**
|
||||
* 字符到字节值的反向映射表,用于解码时快速查找字符对应的索引。
|
||||
*/
|
||||
val codeMap = code.mapIndexed { index, c -> c to index }.toMap()
|
||||
}
|
||||
|
||||
@@ -303,6 +312,13 @@ internal class Base256Codec : BaseCodec {
|
||||
return String(result)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Base256 字符串解码为字节数组。
|
||||
*
|
||||
* @param string 待解码的字符串,所有字符必须属于编码字符集
|
||||
* @return 解码后的字节数组
|
||||
* @throws NullPointerException 如果字符串中包含字符集之外的字符
|
||||
*/
|
||||
override fun decode(string: String): ByteArray {
|
||||
val result = ByteArray(string.length)
|
||||
for (i in string.indices) {
|
||||
|
||||
@@ -22,6 +22,11 @@
|
||||
|
||||
package com.mingliqiye.utils.base
|
||||
|
||||
/**
|
||||
* Base2 编解码器实现类。
|
||||
*
|
||||
* 提供字节数组与二进制字符串(每字节 8 位,高位在前)之间的相互转换功能。
|
||||
*/
|
||||
internal class Base2Codec : BaseCodec {
|
||||
override fun encode(bytes: ByteArray): String {
|
||||
if (bytes.isEmpty()) return ""
|
||||
@@ -34,6 +39,13 @@ internal class Base2Codec : BaseCodec {
|
||||
return result.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* 将二进制字符串解码为字节数组。
|
||||
*
|
||||
* @param string 待解码的二进制字符串,长度必须为 8 的倍数且仅包含字符 '0' 和 '1'
|
||||
* @return 解码后的字节数组
|
||||
* @throws IllegalArgumentException 如果字符串长度不是 8 的倍数或包含非法字符
|
||||
*/
|
||||
override fun decode(string: String): ByteArray {
|
||||
if (string.length % 8 != 0) {
|
||||
throw IllegalArgumentException(
|
||||
|
||||
@@ -24,25 +24,25 @@ package com.mingliqiye.utils.base
|
||||
|
||||
import java.util.*
|
||||
|
||||
/*
|
||||
/**
|
||||
* Base64编解码工具类
|
||||
* 提供Base64编码和解码功能的实现
|
||||
*/
|
||||
internal class Base64Codec : BaseCodec {
|
||||
|
||||
/*
|
||||
/**
|
||||
* Base64编码器实例
|
||||
* 用于执行字节数组到Base64字符串的编码操作
|
||||
*/
|
||||
val encoder: Base64.Encoder = Base64.getEncoder()
|
||||
|
||||
/*
|
||||
/**
|
||||
* Base64解码器实例
|
||||
* 用于执行Base64字符串到字节数组的解码操作
|
||||
*/
|
||||
val decoder: Base64.Decoder = Base64.getDecoder()
|
||||
|
||||
/*
|
||||
/**
|
||||
* 将字节数组编码为Base64字符串
|
||||
*
|
||||
* @param bytes 待编码的字节数组
|
||||
@@ -52,7 +52,7 @@ internal class Base64Codec : BaseCodec {
|
||||
return encoder.encodeToString(bytes)
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* 将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
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile Base64UrlCodec.kt
|
||||
* LastUpdate 2026-03-12 10:34:36
|
||||
* LastUpdate 2026-11-16 14:24:59
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -24,21 +24,26 @@ package com.mingliqiye.utils.base
|
||||
|
||||
import java.util.*
|
||||
|
||||
/**
|
||||
* URL 安全 Base64 编解码器实现类。
|
||||
*
|
||||
* 使用 '-' 和 '_' 替代标准 Base64 中的 '+' 和 '/',适用于 URL 与文件名场景。
|
||||
*/
|
||||
internal class Base64UrlCodec : BaseCodec {
|
||||
|
||||
/*
|
||||
/**
|
||||
* Base64编码器实例
|
||||
* 用于执行字节数组到Base64字符串的编码操作
|
||||
*/
|
||||
val encoder: Base64.Encoder = Base64.getUrlEncoder()
|
||||
|
||||
/*
|
||||
/**
|
||||
* Base64解码器实例
|
||||
* 用于执行Base64字符串到字节数组的解码操作
|
||||
*/
|
||||
val decoder: Base64.Decoder = Base64.getUrlDecoder()
|
||||
|
||||
/*
|
||||
/**
|
||||
* 将字节数组编码为Base64字符串
|
||||
*
|
||||
* @param bytes 待编码的字节数组
|
||||
@@ -48,7 +53,7 @@ internal class Base64UrlCodec : BaseCodec {
|
||||
return encoder.encodeToString(bytes)
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* 将Base64字符串解码为字节数组
|
||||
*
|
||||
* @param string 待解码的Base64字符串
|
||||
|
||||
@@ -29,6 +29,9 @@ package com.mingliqiye.utils.base
|
||||
*/
|
||||
internal class Base91Codec : BaseCodec {
|
||||
|
||||
/**
|
||||
* 伴生对象,持有 Base91 的编码表与解码表。
|
||||
*/
|
||||
companion object {
|
||||
/**
|
||||
* Base91 编码表,共 91 个可打印 ASCII 字符。
|
||||
|
||||
@@ -16,23 +16,55 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile BaseType.kt
|
||||
* LastUpdate 2026-03-12 10:08:42
|
||||
* LastUpdate 2026-11-16 14:21:51
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
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),
|
||||
BASE16(com.mingliqiye.utils.base.code.BASE16),
|
||||
BASE64(com.mingliqiye.utils.base.code.BASE64),
|
||||
BASE64URL(com.mingliqiye.utils.base.code.BASE64URL),
|
||||
BASE91(com.mingliqiye.utils.base.code.BASE91),
|
||||
BASE256(com.mingliqiye.utils.base.code.BASE256);
|
||||
/**
|
||||
* Base 编码类型枚举。
|
||||
*
|
||||
* 每个枚举项持有一个编解码器的工厂函数,枚举本身实现了 [BaseCodec],
|
||||
* 可直接作为编解码器使用,编码与解码操作委托给对应的编解码器实例。
|
||||
*
|
||||
* @param baseCodec 编解码器的工厂函数,每次访问 [codec] 时调用以创建实例
|
||||
*/
|
||||
enum class BaseType(private val baseCodec: () -> BaseCodec) : BaseCodec {
|
||||
|
||||
override fun encode(bytes: ByteArray) = baseCodec.encode(bytes)
|
||||
override fun decode(string: String) = baseCodec.decode(string)
|
||||
/** 二进制(Base2)编解码。 */
|
||||
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
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile BaseCodes.kt
|
||||
* LastUpdate 2026-03-12 10:03:32
|
||||
* LastUpdate 2026-11-16 14:10:57
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -62,11 +62,25 @@ val BASE64: BaseCodec by lazy {
|
||||
Base64Codec()
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供Base64 URL编码器的懒加载实例。
|
||||
* 该编码器用于将数据编码为URL安全的Base64格式。
|
||||
*/
|
||||
@get:JvmName("base64Url")
|
||||
val BASE64URL: BaseCodec by lazy {
|
||||
val BASE64_URL: BaseCodec by lazy {
|
||||
Base64UrlCodec()
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供无填充Base64 URL编码器的懒加载实例。
|
||||
* 该编码器用于将数据编码为URL安全的Base64格式,且结果不带末尾的'='填充字符。
|
||||
*/
|
||||
@get:JvmName("base64NoPadding")
|
||||
val BASE64_NO_PADDING: BaseCodec by lazy {
|
||||
Base64NoPaddingCodec()
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 提供Base91编码器的懒加载实例。
|
||||
* 该编码器用于将数据编码为Base91格式,具有较高的压缩效率。
|
||||
|
||||
@@ -29,31 +29,69 @@ import java.security.SecureRandom
|
||||
import org.mindrot.jbcrypt.BCrypt as JBCrypt
|
||||
|
||||
|
||||
/**
|
||||
* 使用随机生成的盐对字符串进行 BCrypt 哈希。
|
||||
*
|
||||
* @param string 需要哈希的明文字符串
|
||||
* @return BCrypt 哈希字符串
|
||||
*/
|
||||
fun hashpw(string: String): String {
|
||||
return hashpw(string, gensalt())
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 使用指定的盐对字符串进行 BCrypt 哈希。
|
||||
*
|
||||
* @param string 需要哈希的明文字符串
|
||||
* @param salt BCrypt 盐字符串,默认随机生成
|
||||
* @return BCrypt 哈希字符串
|
||||
*/
|
||||
fun hashpw(string: String, salt: String = gensalt()): String {
|
||||
return JBCrypt.hashpw(string, salt)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 验证明文字符串与 BCrypt 哈希是否匹配。
|
||||
*
|
||||
* @param string 明文字符串
|
||||
* @param bcrypted 已生成的 BCrypt 哈希字符串
|
||||
* @return 匹配返回 true,否则返回 false
|
||||
*/
|
||||
fun checkpw(string: String, bcrypted: String): Boolean {
|
||||
return JBCrypt.checkpw(string, bcrypted)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 生成默认工作因子(10)的 BCrypt 盐。
|
||||
*
|
||||
* @return BCrypt 盐字符串
|
||||
*/
|
||||
fun gensalt(): String {
|
||||
return JBCrypt.gensalt()
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 生成指定工作因子的 BCrypt 盐。
|
||||
*
|
||||
* @param long 工作因子(log2 迭代次数),值越大计算越慢
|
||||
* @return BCrypt 盐字符串
|
||||
*/
|
||||
fun gensalt(long: Int): String {
|
||||
return JBCrypt.gensalt(long)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 使用指定的安全随机数生成器生成 BCrypt 盐。
|
||||
*
|
||||
* @param long 工作因子(log2 迭代次数)
|
||||
* @param secureRandom 用于生成盐的安全随机数生成器
|
||||
* @return BCrypt 盐字符串
|
||||
*/
|
||||
fun gensalt(long: Int, secureRandom: SecureRandom): String {
|
||||
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()}"
|
||||
}
|
||||
|
||||
/**
|
||||
* 伴生对象,提供工厂方法以及类型转换器的注册与查询功能。
|
||||
*/
|
||||
companion object {
|
||||
/**
|
||||
* 包装现有的 ByteBuffer
|
||||
@@ -279,6 +282,11 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
|
||||
byteBufferWrapperConvertor
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加转换器到映射表,通过具体化类型参数自动创建转换器实例
|
||||
*
|
||||
* @param T 转换器类型,必须提供无参构造函数
|
||||
*/
|
||||
@JvmName("inline_addConvertor")
|
||||
inline fun <reified T : ByteBufferWrapperConvertor<*>> addConvertor() {
|
||||
addConvertor(ByteBufferWrapperConvertor.getInstantiation<T>())
|
||||
@@ -537,24 +545,64 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
|
||||
return convertor.read(this, parameters)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从缓冲区中读取指定类型的对象(不带额外参数)
|
||||
*
|
||||
* @param clazz 要读取的对象类型对应的 Class 对象
|
||||
* @param T 要读取的对象类型
|
||||
* @return 读取并转换后的 T 类型对象
|
||||
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
|
||||
*/
|
||||
fun <T : Any> getObject(clazz: Class<T>): T {
|
||||
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 {
|
||||
return getObject(clazz, arrayOf(size))
|
||||
}
|
||||
|
||||
/**
|
||||
* 从缓冲区中读取具体化类型 T 的对象,并传入额外参数
|
||||
*
|
||||
* @param parameters 传递给转换器的参数数组
|
||||
* @param T 要读取的对象类型
|
||||
* @return 读取并转换后的 T 类型对象
|
||||
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
|
||||
*/
|
||||
@JvmName("inline_getObject")
|
||||
inline fun <reified T : Any> getObject(parameters: Array<Any>): T {
|
||||
return getObject(T::class.java, parameters)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从缓冲区中读取具体化类型 T 的对象,并传入长度参数
|
||||
*
|
||||
* @param size 读取长度(如数组元素个数),作为转换器的第一个参数
|
||||
* @param T 要读取的对象类型
|
||||
* @return 读取并转换后的 T 类型对象
|
||||
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
|
||||
*/
|
||||
@JvmName("inline_getObject")
|
||||
inline fun <reified T : Any> getObject(size: Int): T {
|
||||
return getObject(T::class.java, size)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从缓冲区中读取具体化类型 T 的对象(不带额外参数)
|
||||
*
|
||||
* @param T 要读取的对象类型
|
||||
* @return 读取并转换后的 T 类型对象
|
||||
* @throws IllegalArgumentException 如果该类型没有注册对应的转换器
|
||||
*/
|
||||
@JvmName("inline_getObject")
|
||||
inline fun <reified T : Any> getObject(): T {
|
||||
return getObject(T::class.java)
|
||||
@@ -574,11 +622,24 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 按初始化函数生成指定长度的字节数组并写入缓冲区
|
||||
*
|
||||
* @param size 要生成并写入的字节数
|
||||
* @param init 初始化函数,根据索引生成每个字节的值
|
||||
* @return 当前对象(支持链式调用)
|
||||
*/
|
||||
fun putByteArray(size: Int, init: (Int) -> Byte): ByteBufferWrapper {
|
||||
buffer.put(ByteArray(size, init))
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字符数组完整写入缓冲区(每个字符取低 8 位,1字节)
|
||||
*
|
||||
* @param charArray 要写入的字符数组
|
||||
* @return 当前对象(支持链式调用)
|
||||
*/
|
||||
fun putCharArray(charArray: CharArray): ByteBufferWrapper {
|
||||
putByteArray(charArray.size) {
|
||||
charArray[it].code.toByte()
|
||||
@@ -586,6 +647,12 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取指定长度的字符数组(每个字节转换为一个字符)
|
||||
*
|
||||
* @param size 要读取的字符数
|
||||
* @return 读取的字符数组
|
||||
*/
|
||||
fun getCharArray(size: Int): CharArray {
|
||||
return getByteArray(size).let {
|
||||
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 {
|
||||
intArray.forEach(::putInt)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取指定长度的整数数组
|
||||
*
|
||||
* @param size 要读取的整数个数
|
||||
* @return 读取的整数数组
|
||||
*/
|
||||
fun getIntArray(size: Int): IntArray {
|
||||
return IntArray(size) { getInt() }
|
||||
}
|
||||
|
||||
/**
|
||||
* 将短整数数组完整写入缓冲区(每个短整数2字节)
|
||||
*
|
||||
* @param shortArray 要写入的短整数数组
|
||||
* @return 当前对象(支持链式调用)
|
||||
*/
|
||||
fun putShortArray(shortArray: ShortArray): ByteBufferWrapper {
|
||||
shortArray.forEach(::putShort)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取指定长度的短整数数组
|
||||
*
|
||||
* @param size 要读取的短整数个数
|
||||
* @return 读取的短整数数组
|
||||
*/
|
||||
fun getShortArray(size: Int): ShortArray {
|
||||
return ShortArray(size) { getShort() }
|
||||
}
|
||||
|
||||
/**
|
||||
* 将长整数数组完整写入缓冲区(每个长整数8字节)
|
||||
*
|
||||
* @param longArray 要写入的长整数数组
|
||||
* @return 当前对象(支持链式调用)
|
||||
*/
|
||||
fun putLongArray(longArray: LongArray): ByteBufferWrapper {
|
||||
longArray.forEach(::putLong)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取指定长度的长整数数组
|
||||
*
|
||||
* @param size 要读取的长整数个数
|
||||
* @return 读取的长整数数组
|
||||
*/
|
||||
fun getLongArray(size: Int): LongArray {
|
||||
return LongArray(size) { getLong() }
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将双精度浮点数数组完整写入缓冲区(每个浮点数8字节)
|
||||
*
|
||||
* @param doubleArray 要写入的双精度浮点数数组
|
||||
* @return 当前对象(支持链式调用)
|
||||
*/
|
||||
fun putDoubleArray(doubleArray: DoubleArray): ByteBufferWrapper {
|
||||
doubleArray.forEach(::putDouble)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取指定长度的双精度浮点数数组
|
||||
*
|
||||
* @param size 要读取的双精度浮点数个数
|
||||
* @return 读取的双精度浮点数数组
|
||||
*/
|
||||
fun getDoubleArray(size: Int): DoubleArray {
|
||||
return DoubleArray(size) { getDouble() }
|
||||
}
|
||||
|
||||
/**
|
||||
* 将单精度浮点数数组完整写入缓冲区(每个浮点数4字节)
|
||||
*
|
||||
* @param floatArray 要写入的单精度浮点数数组
|
||||
* @return 当前对象(支持链式调用)
|
||||
*/
|
||||
fun putFloatArray(floatArray: FloatArray): ByteBufferWrapper {
|
||||
floatArray.forEach(::putFloat)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取指定长度的单精度浮点数数组
|
||||
*
|
||||
* @param size 要读取的单精度浮点数个数
|
||||
* @return 读取的单精度浮点数数组
|
||||
*/
|
||||
fun getFloatArray(size: Int): FloatArray {
|
||||
return FloatArray(size) { getFloat() }
|
||||
}
|
||||
|
||||
/**
|
||||
* 将布尔数组完整写入缓冲区(每个布尔值1字节,true = 0x01,false = 0x00)
|
||||
*
|
||||
* @param booleanArray 要写入的布尔数组
|
||||
* @return 当前对象(支持链式调用)
|
||||
*/
|
||||
fun putBooleanArray(booleanArray: BooleanArray): ByteBufferWrapper {
|
||||
putByteArray(booleanArray.size) {
|
||||
if (booleanArray[it]) 0x01 else 0x00
|
||||
@@ -647,6 +780,13 @@ class ByteBufferWrapper private constructor(private val buffer: ByteBuffer) {
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取指定长度的布尔数组
|
||||
*
|
||||
* @param size 要读取的布尔值个数
|
||||
* @return 读取的布尔数组
|
||||
* @throws IllegalArgumentException 如果读取到的字节值不是 0x00 或 0x01
|
||||
*/
|
||||
fun getBooleanArray(size: Int): BooleanArray {
|
||||
return getByteArray(size).let {
|
||||
BooleanArray(it.size) { index ->
|
||||
|
||||
@@ -33,21 +33,67 @@ import java.util.*
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.UUID as JUUID
|
||||
|
||||
/**
|
||||
* ByteBufferWrapper 类型转换器接口。
|
||||
*
|
||||
* 定义某种类型与 [ByteBufferWrapper] 之间的读写规则。
|
||||
*
|
||||
* @param T 该转换器处理的数据类型
|
||||
*/
|
||||
interface ByteBufferWrapperConvertorInterface<T : Any> {
|
||||
/**
|
||||
* 将对象写入缓冲区。
|
||||
*
|
||||
* @param obj 要写入的对象
|
||||
* @param byteBufferWrapper 目标缓冲区包装器
|
||||
*/
|
||||
fun write(obj: T, byteBufferWrapper: ByteBufferWrapper)
|
||||
|
||||
/**
|
||||
* 从缓冲区中读取对象。
|
||||
*
|
||||
* @param byteBufferWrapper 源缓冲区包装器
|
||||
* @param parameters 读取时需要的额外参数(如数组长度)
|
||||
* @return 读取并转换后的对象
|
||||
*/
|
||||
fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T
|
||||
|
||||
/**
|
||||
* 获取该转换器处理的数据类型。
|
||||
*
|
||||
* @return 类型对应的 Class 对象
|
||||
*/
|
||||
fun getType(): Class<T>
|
||||
}
|
||||
|
||||
/**
|
||||
* ByteBufferWrapper 类型转换器抽象基类。
|
||||
*
|
||||
* 提供转换器实例的缓存创建以及默认转换器的注册功能。
|
||||
*
|
||||
* @param T 该转换器处理的数据类型
|
||||
*/
|
||||
abstract class ByteBufferWrapperConvertor<T : Any> : ByteBufferWrapperConvertorInterface<T> {
|
||||
/**
|
||||
* 返回包含所处理类型信息的字符串表示。
|
||||
*/
|
||||
override fun toString(): String {
|
||||
return "ByteBufferWrapperConvertor(type=${getType()})"
|
||||
}
|
||||
|
||||
/**
|
||||
* 伴生对象,管理转换器实例缓存并提供默认转换器安装方法。
|
||||
*/
|
||||
companion object {
|
||||
private val _instantiations =
|
||||
ConcurrentHashMap<Class<ByteBufferWrapperConvertor<*>>, ByteBufferWrapperConvertor<*>>()
|
||||
|
||||
/**
|
||||
* 获取指定转换器类的实例,不存在时通过无参构造函数创建并缓存。
|
||||
*
|
||||
* @param clazz 转换器类对应的 Class 对象
|
||||
* @return 缓存的或新创建的转换器实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun getInstantiation(clazz: Class<ByteBufferWrapperConvertor<*>>): ByteBufferWrapperConvertor<*> {
|
||||
return _instantiations.getOrPut(clazz) {
|
||||
@@ -55,12 +101,23 @@ abstract class ByteBufferWrapperConvertor<T : Any> : ByteBufferWrapperConvertorI
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取具体化类型 T 对应的转换器实例,不存在时创建并缓存。
|
||||
*
|
||||
* @param T 转换器类型,必须提供无参构造函数
|
||||
* @return 缓存的或新创建的转换器实例
|
||||
*/
|
||||
@JvmStatic
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
inline fun <reified T : ByteBufferWrapperConvertor<*>> getInstantiation(): ByteBufferWrapperConvertor<*> {
|
||||
return getInstantiation(T::class.java as Class<ByteBufferWrapperConvertor<*>>)
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装所有默认转换器。
|
||||
*
|
||||
* 将基础类型、大数、字符串、时间、UUID 及各类数组的转换器注册到 [ByteBufferWrapper]。
|
||||
*/
|
||||
fun defaultConvertorInstall() {
|
||||
ByteBufferWrapper.addConvertor<BigDecimalBufferWrapperConvertor>()
|
||||
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>(
|
||||
val write: ByteBufferWrapper.(obj: T) -> Unit,
|
||||
val read: ByteBufferWrapper.() -> T,
|
||||
@@ -104,72 +171,84 @@ abstract class ObjectBufferWrapperConvertor<T : Any>(
|
||||
}
|
||||
|
||||
|
||||
/** [Byte] 类型转换器,使用 putByte/getByte 读写。 */
|
||||
class BytedBufferWrapperConvertor : ObjectBufferWrapperConvertor<Byte>(
|
||||
ByteBufferWrapper::putByte,
|
||||
ByteBufferWrapper::getByte,
|
||||
Byte::class.java,
|
||||
)
|
||||
|
||||
/** [Char] 类型转换器,使用 putChar/getChar 读写。 */
|
||||
class CharBufferWrapperConvertor : ObjectBufferWrapperConvertor<Char>(
|
||||
ByteBufferWrapper::putChar,
|
||||
ByteBufferWrapper::getChar,
|
||||
Char::class.java,
|
||||
)
|
||||
|
||||
/** [Short] 类型转换器,使用 putShort/getShort 读写。 */
|
||||
class ShortBufferWrapperConvertor : ObjectBufferWrapperConvertor<Short>(
|
||||
ByteBufferWrapper::putShort,
|
||||
ByteBufferWrapper::getShort,
|
||||
Short::class.java,
|
||||
)
|
||||
|
||||
/** [Int] 类型转换器,使用 putInt/getInt 读写。 */
|
||||
class IntBufferWrapperConvertor : ObjectBufferWrapperConvertor<Int>(
|
||||
ByteBufferWrapper::putInt,
|
||||
ByteBufferWrapper::getInt,
|
||||
Int::class.java,
|
||||
)
|
||||
|
||||
/** [Long] 类型转换器,使用 putLong/getLong 读写。 */
|
||||
class LongBufferWrapperConvertor : ObjectBufferWrapperConvertor<Long>(
|
||||
ByteBufferWrapper::putLong,
|
||||
ByteBufferWrapper::getLong,
|
||||
Long::class.java,
|
||||
)
|
||||
|
||||
/** [Double] 类型转换器,使用 putDouble/getDouble 读写。 */
|
||||
class DoubleBufferWrapperConvertor : ObjectBufferWrapperConvertor<Double>(
|
||||
ByteBufferWrapper::putDouble,
|
||||
ByteBufferWrapper::getDouble,
|
||||
Double::class.java,
|
||||
)
|
||||
|
||||
/** [Float] 类型转换器,使用 putFloat/getFloat 读写。 */
|
||||
class FloatBufferWrapperConvertor : ObjectBufferWrapperConvertor<Float>(
|
||||
ByteBufferWrapper::putFloat,
|
||||
ByteBufferWrapper::getFloat,
|
||||
Float::class.java,
|
||||
)
|
||||
|
||||
/** [BigInteger] 类型转换器,使用 putBigInteger/getBigInteger 读写。 */
|
||||
class BigIntegerBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigInteger>(
|
||||
ByteBufferWrapper::putBigInteger,
|
||||
ByteBufferWrapper::getBigInteger,
|
||||
BigInteger::class.java,
|
||||
)
|
||||
|
||||
/** [BigDecimal] 类型转换器,使用 putBigDecimal/getBigDecimal 读写。 */
|
||||
class BigDecimalBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigDecimal>(
|
||||
ByteBufferWrapper::putBigDecimal,
|
||||
ByteBufferWrapper::getBigDecimal,
|
||||
BigDecimal::class.java,
|
||||
)
|
||||
|
||||
/** [Boolean] 类型转换器,使用 putBoolean/getBoolean 读写。 */
|
||||
class BooleanBufferWrapperConvertor : ObjectBufferWrapperConvertor<Boolean>(
|
||||
ByteBufferWrapper::putBoolean,
|
||||
ByteBufferWrapper::getBoolean,
|
||||
Boolean::class.java,
|
||||
)
|
||||
|
||||
/** [String] 类型转换器,使用 putString/getString 读写。 */
|
||||
class StringBufferWrapperConvertor : ObjectBufferWrapperConvertor<String>(
|
||||
ByteBufferWrapper::putString,
|
||||
ByteBufferWrapper::getString,
|
||||
String::class.java,
|
||||
)
|
||||
|
||||
/** [ByteFlags] 类型转换器,使用 putFlag/getFlag 读写。 */
|
||||
class ByteFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<ByteFlags>(
|
||||
ByteBufferWrapper::putFlag,
|
||||
ByteBufferWrapper::getFlag,
|
||||
@@ -177,42 +256,62 @@ class ByteFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<ByteFlags>(
|
||||
)
|
||||
|
||||
|
||||
/** Java [JUUID] 类型转换器,使用 putUUID/getJUUID 读写。 */
|
||||
class JUUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<JUUID>(
|
||||
ByteBufferWrapper::putUUID,
|
||||
ByteBufferWrapper::getJUUID,
|
||||
JUUID::class.java,
|
||||
)
|
||||
|
||||
/** 自定义 [UUID] 类型转换器,使用 putUUID/getUUID 读写。 */
|
||||
class UUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<UUID>(
|
||||
ByteBufferWrapper::putUUID,
|
||||
ByteBufferWrapper::getUUID,
|
||||
UUID::class.java,
|
||||
)
|
||||
|
||||
/** [DateTime] 类型转换器,使用 putDateTime/getDateTime 读写。 */
|
||||
class DateTimeFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<DateTime>(
|
||||
ByteBufferWrapper::putDateTime,
|
||||
ByteBufferWrapper::getDateTime,
|
||||
DateTime::class.java,
|
||||
)
|
||||
|
||||
/** [LocalDateTime] 类型转换器,使用 putLocalDateTime/getLocalDateTime 读写。 */
|
||||
class LocalDateTimeBufferWrapperConvertor : ObjectBufferWrapperConvertor<LocalDateTime>(
|
||||
ByteBufferWrapper::putLocalDateTime,
|
||||
ByteBufferWrapper::getLocalDateTime,
|
||||
LocalDateTime::class.java,
|
||||
)
|
||||
|
||||
/** [Date] 类型转换器,使用 putDate/getDate 读写。 */
|
||||
class DateBufferWrapperConvertor : ObjectBufferWrapperConvertor<Date>(
|
||||
ByteBufferWrapper::putDate,
|
||||
ByteBufferWrapper::getDate,
|
||||
Date::class.java,
|
||||
)
|
||||
|
||||
/**
|
||||
* 基于读写函数构造的通用数组转换器。
|
||||
*
|
||||
* 读取时要求额外参数的第一个元素为 Int 类型的数组长度。
|
||||
*
|
||||
* @param T 该转换器处理的数组类型
|
||||
* @param write 写入函数,将数组写入缓冲区
|
||||
* @param read 读取函数,按指定长度从缓冲区读取数组
|
||||
* @param typer 该转换器处理的数组类型对应的 Class 对象
|
||||
*/
|
||||
abstract class ArrayBufferWrapperConvertor<T : Any>(
|
||||
val write: ByteBufferWrapper.(obj: T) -> Unit,
|
||||
val read: ByteBufferWrapper.(size: Int) -> T,
|
||||
val typer: Class<T>,
|
||||
) : ByteBufferWrapperConvertor<T>() {
|
||||
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 {
|
||||
if (parameters.isEmpty()) {
|
||||
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
|
||||
}
|
||||
|
||||
/** [ByteArray] 类型转换器,使用 putByteArray/getByteArray 读写。 */
|
||||
class ByteArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ByteArray>(
|
||||
ByteBufferWrapper::putByteArray,
|
||||
ByteBufferWrapper::getByteArray,
|
||||
ByteArray::class.java,
|
||||
)
|
||||
|
||||
/** [CharArray] 类型转换器,使用 putCharArray/getCharArray 读写。 */
|
||||
class CharArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<CharArray>(
|
||||
ByteBufferWrapper::putCharArray,
|
||||
ByteBufferWrapper::getCharArray,
|
||||
CharArray::class.java,
|
||||
)
|
||||
|
||||
/** [ShortArray] 类型转换器,使用 putShortArray/getShortArray 读写。 */
|
||||
class ShortArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ShortArray>(
|
||||
ByteBufferWrapper::putShortArray,
|
||||
ByteBufferWrapper::getShortArray,
|
||||
ShortArray::class.java,
|
||||
)
|
||||
|
||||
/** [IntArray] 类型转换器,使用 putIntArray/getIntArray 读写。 */
|
||||
class IntArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<IntArray>(
|
||||
ByteBufferWrapper::putIntArray,
|
||||
ByteBufferWrapper::getIntArray,
|
||||
IntArray::class.java,
|
||||
)
|
||||
|
||||
/** [LongArray] 类型转换器,使用 putLongArray/getLongArray 读写。 */
|
||||
class LongArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<LongArray>(
|
||||
ByteBufferWrapper::putLongArray,
|
||||
ByteBufferWrapper::getLongArray,
|
||||
LongArray::class.java,
|
||||
)
|
||||
|
||||
/** [FloatArray] 类型转换器,使用 putFloatArray/getFloatArray 读写。 */
|
||||
class FloatArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<FloatArray>(
|
||||
ByteBufferWrapper::putFloatArray,
|
||||
ByteBufferWrapper::getFloatArray,
|
||||
FloatArray::class.java,
|
||||
)
|
||||
|
||||
/** [DoubleArray] 类型转换器,使用 putDoubleArray/getDoubleArray 读写。 */
|
||||
class DoubleArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<DoubleArray>(
|
||||
ByteBufferWrapper::putDoubleArray,
|
||||
ByteBufferWrapper::getDoubleArray,
|
||||
@@ -269,6 +375,7 @@ class DoubleArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<DoubleArra
|
||||
)
|
||||
|
||||
|
||||
/** [BooleanArray] 类型转换器,使用 putBooleanArray/getBooleanArray 读写。 */
|
||||
class BooleanArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<BooleanArray>(
|
||||
ByteBufferWrapper::putBooleanArray,
|
||||
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())
|
||||
|
||||
|
||||
/**
|
||||
* 将 [ByteBuffer] 中剩余的全部字节写入指定的输出流。
|
||||
*
|
||||
* 此操作会读取从当前位置到 limit 之间的所有字节,并推进 position。
|
||||
*
|
||||
* @param outputStream 目标输出流
|
||||
* @throws IOException 如果写入过程中发生 I/O 错误
|
||||
*/
|
||||
fun ByteBuffer.writeStream(outputStream: OutputStream) = outputStream.write(this.toByteArray())
|
||||
|
||||
@@ -26,23 +26,56 @@ import java.io.OutputStream
|
||||
import java.io.Serializable
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/**
|
||||
* 可转换为字节数组的对象接口。
|
||||
*
|
||||
* 实现该接口的对象可以将自身序列化为字节数组,并支持写入输出流或 [ByteBuffer]。
|
||||
*/
|
||||
interface ByteConvertible : Serializable {
|
||||
|
||||
/**
|
||||
* 将当前对象转换为字节数组。
|
||||
*
|
||||
* @return 表示当前对象的字节数组
|
||||
*/
|
||||
fun toBytes(): ByteArray
|
||||
|
||||
/**
|
||||
* 将当前对象转换后的字节数组写入指定的输出流。
|
||||
*
|
||||
* @param outputStream 目标输出流
|
||||
*/
|
||||
fun writeToStream(outputStream: OutputStream) {
|
||||
outputStream.write(toBytes())
|
||||
}
|
||||
|
||||
/**
|
||||
* 将当前对象转换后的字节数组写入指定的 [ByteBuffer]。
|
||||
*
|
||||
* @param byteBuffer 目标缓冲区
|
||||
*/
|
||||
fun putToByteBuffer(byteBuffer: ByteBuffer) {
|
||||
byteBuffer.put(toBytes())
|
||||
}
|
||||
|
||||
/**
|
||||
* 伴生对象,提供面向输出流和缓冲区的便捷扩展函数。
|
||||
*/
|
||||
companion object {
|
||||
/**
|
||||
* 将 [ByteConvertible] 对象写入当前输出流。
|
||||
*
|
||||
* @param byteConvertible 要写入的可转换对象
|
||||
*/
|
||||
fun OutputStream.write(byteConvertible: ByteConvertible) {
|
||||
byteConvertible.writeToStream(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 [ByteConvertible] 对象写入当前 [ByteBuffer]。
|
||||
*
|
||||
* @param byteConvertible 要写入的可转换对象
|
||||
*/
|
||||
fun ByteBuffer.put(byteConvertible: ByteConvertible) {
|
||||
byteConvertible.putToByteBuffer(this)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile ByteFlags.kt
|
||||
* LastUpdate 2026-06-21 10:40:58
|
||||
* LastUpdate 2026-11-16 21:35:04
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -64,7 +64,7 @@ data class ByteFlags(
|
||||
*
|
||||
* @param byte 要解析的字节
|
||||
*/
|
||||
fun fromByte(byte: Byte) {
|
||||
fun fromByte(byte: Byte): ByteFlags {
|
||||
val value = byte.toInt() and 0xFF
|
||||
b0 = (value and 0x01) != 0
|
||||
b1 = (value and 0x02) != 0
|
||||
@@ -74,6 +74,7 @@ data class ByteFlags(
|
||||
b5 = (value and 0x20) != 0
|
||||
b6 = (value and 0x40) != 0
|
||||
b7 = (value and 0x80) != 0
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -122,7 +123,7 @@ data class ByteFlags(
|
||||
* @param value 要设置的布尔值
|
||||
* @throws IndexOutOfBoundsException 如果索引不在 0~7 范围内
|
||||
*/
|
||||
operator fun set(index: Int, value: Boolean) {
|
||||
operator fun set(index: Int, value: Boolean): ByteFlags {
|
||||
when (index) {
|
||||
0 -> b0 = value
|
||||
1 -> b1 = value
|
||||
@@ -134,12 +135,13 @@ data class ByteFlags(
|
||||
7 -> b7 = value
|
||||
else -> throw IndexOutOfBoundsException("索引必须在0-7之间")
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 将所有 8 个位设置为 `true`。
|
||||
*/
|
||||
fun setAll() {
|
||||
fun setAll(): ByteFlags {
|
||||
b0 = true
|
||||
b1 = true
|
||||
b2 = true
|
||||
@@ -148,12 +150,14 @@ data class ByteFlags(
|
||||
b5 = true
|
||||
b6 = true
|
||||
b7 = true
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 将所有 8 个位设置为 `false`。
|
||||
*/
|
||||
fun clearAll() {
|
||||
fun clearAll(): ByteFlags {
|
||||
b0 = false
|
||||
b1 = false
|
||||
b2 = false
|
||||
@@ -162,12 +166,14 @@ data class ByteFlags(
|
||||
b5 = false
|
||||
b6 = false
|
||||
b7 = false
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 对所有位执行逻辑取反(true ↔ false)。
|
||||
*/
|
||||
fun toggleAll() {
|
||||
fun toggleAll(): ByteFlags {
|
||||
b0 = !b0
|
||||
b1 = !b1
|
||||
b2 = !b2
|
||||
@@ -176,6 +182,8 @@ data class ByteFlags(
|
||||
b5 = !b5
|
||||
b6 = !b6
|
||||
b7 = !b7
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -184,8 +192,9 @@ data class ByteFlags(
|
||||
* @param index 要切换的位索引(0~7)
|
||||
* @throws IndexOutOfBoundsException 如果索引无效
|
||||
*/
|
||||
fun toggle(index: Int) {
|
||||
fun toggle(index: Int): ByteFlags {
|
||||
this[index] = !this[index]
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -304,7 +313,7 @@ data class ByteFlags(
|
||||
* @param array 布尔数组(长度至少为 8)
|
||||
* @throws IllegalArgumentException 如果数组长度不足 8
|
||||
*/
|
||||
fun fromBooleanArray(array: BooleanArray) {
|
||||
fun fromBooleanArray(array: BooleanArray): ByteFlags {
|
||||
require(array.size >= 8) { "数组长度至少为8" }
|
||||
b0 = array[0]
|
||||
b1 = array[1]
|
||||
@@ -314,6 +323,7 @@ data class ByteFlags(
|
||||
b5 = array[5]
|
||||
b6 = array[6]
|
||||
b7 = array[7]
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -403,6 +413,9 @@ data class ByteFlags(
|
||||
return "ByteFlags(${toBinaryString()} = ${toHexString()})"
|
||||
}
|
||||
|
||||
/**
|
||||
* 伴生对象,提供 [ByteFlags] 的多种静态工厂方法。
|
||||
*/
|
||||
companion object {
|
||||
/**
|
||||
* 创建一个所有位均为 `true` 的 [ByteFlags] 实例。
|
||||
@@ -434,7 +447,6 @@ data class ByteFlags(
|
||||
fun fromBinaryString(binary: String): ByteFlags {
|
||||
require(binary.length == 8) { "二进制字符串长度必须为8" }
|
||||
require(binary.all { it == '0' || it == '1' }) { "二进制字符串只能包含0和1" }
|
||||
|
||||
return ByteFlags(
|
||||
binary[7] == '1', // b0 是最低位(对应字符串最后一位)
|
||||
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 位)。
|
||||
*
|
||||
|
||||
@@ -28,11 +28,24 @@ import com.mingliqiye.utils.json.api.JSONA
|
||||
import java.io.*
|
||||
|
||||
|
||||
/**
|
||||
* 通过 Java 序列化机制对当前对象进行深克隆。
|
||||
*
|
||||
* @param T 对象类型,必须实现 [Serializable]
|
||||
* @return 深克隆后的新对象
|
||||
*/
|
||||
@JvmName("_inline_deepClone")
|
||||
inline fun <reified T : Serializable> T.deepClone(): T {
|
||||
return deepClone(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 JSON 序列化与反序列化对当前对象进行深克隆。
|
||||
*
|
||||
* @param T 对象类型
|
||||
* @return 深克隆后的新对象
|
||||
* @throws JsonException 如果 JSON 转换过程中发生异常
|
||||
*/
|
||||
inline fun <reified T> T.deepJsonClone(): T {
|
||||
try {
|
||||
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")
|
||||
fun <T : Serializable?> deepClone(obj: T): T {
|
||||
try {
|
||||
|
||||
@@ -158,7 +158,7 @@ inline fun <reified T> Array<T>.getLast(): T? {
|
||||
* @return 指定索引处的元素或默认值
|
||||
*/
|
||||
inline fun <reified T> Collection<T>.getOrDefault(
|
||||
index: Int, defaultValue: T
|
||||
index: Int, defaultValue: T,
|
||||
): T {
|
||||
if (!(!this.isEmpty() && index < this.size)) {
|
||||
return defaultValue
|
||||
@@ -987,6 +987,14 @@ inline fun <reified T> toArray(list: List<T>): Array<T> {
|
||||
.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> {
|
||||
return SuperStream.of<T>(list)
|
||||
.toArray(clazz)
|
||||
|
||||
@@ -39,6 +39,9 @@ class IsChanged<T> {
|
||||
*/
|
||||
private val atomicReferenceData: AtomicReference<T> = AtomicReference()
|
||||
|
||||
/**
|
||||
* 无参构造函数,初始数据为 null
|
||||
*/
|
||||
constructor()
|
||||
|
||||
/**
|
||||
|
||||
@@ -63,6 +63,9 @@ private fun getGetterName(fieldName: String): String {
|
||||
*/
|
||||
open class ConfigurationProps {
|
||||
|
||||
/**
|
||||
* 伴生对象,提供根据命令行参数初始化配置类实例的静态方法。
|
||||
*/
|
||||
companion object {
|
||||
/**
|
||||
* 初始化配置类实例,并根据命令行参数填充其字段。
|
||||
@@ -241,6 +244,9 @@ open class ConfigurationProps {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印配置项帮助信息,列出所有标注了 ConfigurationProp 且允许显示帮助的字段名称、类型和描述。
|
||||
*/
|
||||
fun printHelp() {
|
||||
val fields = this::class.java.declaredFields
|
||||
val help = StringBuilder()
|
||||
@@ -258,6 +264,9 @@ open class ConfigurationProps {
|
||||
println(help)
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前配置对象所有声明字段的名称与值的映射。
|
||||
*/
|
||||
val fields: Map<String, Any?>
|
||||
get() {
|
||||
val fields = this::class.java.declaredFields
|
||||
|
||||
@@ -143,4 +143,3 @@ private fun getAllFields(clazz: Class<*>): List<Field> {
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,14 @@
|
||||
|
||||
package com.mingliqiye.utils.exception
|
||||
|
||||
/**
|
||||
* 表示编码或解码过程中发生的异常。
|
||||
*
|
||||
* @param message 异常信息,默认为 null
|
||||
* @param throwable 异常原因,默认为 null
|
||||
* @param enableSuppression 是否启用异常抑制,默认为 false
|
||||
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
|
||||
*/
|
||||
class CodecException @JvmOverloads constructor(
|
||||
message: String? = null,
|
||||
throwable: Throwable? = null,
|
||||
|
||||
@@ -22,6 +22,14 @@
|
||||
|
||||
package com.mingliqiye.utils.exception
|
||||
|
||||
/**
|
||||
* 表示 JSON 内容为空时抛出的异常。
|
||||
*
|
||||
* @param message 异常信息,默认为 null
|
||||
* @param throwable 异常原因,默认为 null
|
||||
* @param enableSuppression 是否启用异常抑制,默认为 false
|
||||
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
|
||||
*/
|
||||
class EmptyJsonException @JvmOverloads constructor(
|
||||
message: String? = null,
|
||||
throwable: Throwable? = null,
|
||||
|
||||
@@ -22,6 +22,14 @@
|
||||
|
||||
package com.mingliqiye.utils.exception
|
||||
|
||||
/**
|
||||
* 表示 HTTP 相关异常的基类,继承自 [MingLiUtilsBaseException]。
|
||||
*
|
||||
* @param message 异常信息,默认为 null
|
||||
* @param throwable 异常原因,默认为 null
|
||||
* @param enableSuppression 是否启用异常抑制,默认为 false
|
||||
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
|
||||
*/
|
||||
open class HttpException @JvmOverloads constructor(
|
||||
message: String? = null,
|
||||
throwable: Throwable? = null,
|
||||
|
||||
@@ -22,6 +22,14 @@
|
||||
|
||||
package com.mingliqiye.utils.exception
|
||||
|
||||
/**
|
||||
* 表示 HTTP URL 无效或处理失败时抛出的异常。
|
||||
*
|
||||
* @param message 异常信息,默认为 null
|
||||
* @param throwable 异常原因,默认为 null
|
||||
* @param enableSuppression 是否启用异常抑制,默认为 false
|
||||
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
|
||||
*/
|
||||
open class HttpUrlException @JvmOverloads constructor(
|
||||
message: String? = null,
|
||||
throwable: Throwable? = null,
|
||||
|
||||
@@ -22,6 +22,14 @@
|
||||
|
||||
package com.mingliqiye.utils.exception
|
||||
|
||||
/**
|
||||
* 表示 JSON 内容无效或不合法时抛出的异常。
|
||||
*
|
||||
* @param message 异常信息,默认为 null
|
||||
* @param throwable 异常原因,默认为 null
|
||||
* @param enableSuppression 是否启用异常抑制,默认为 false
|
||||
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
|
||||
*/
|
||||
class InvalidJsonException @JvmOverloads constructor(
|
||||
message: String? = null,
|
||||
throwable: Throwable? = null,
|
||||
|
||||
@@ -22,6 +22,14 @@
|
||||
|
||||
package com.mingliqiye.utils.exception
|
||||
|
||||
/**
|
||||
* 表示 JSON 对象类型转换失败时抛出的异常。
|
||||
*
|
||||
* @param message 异常信息,默认为 null
|
||||
* @param throwable 异常原因,默认为 null
|
||||
* @param enableSuppression 是否启用异常抑制,默认为 false
|
||||
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
|
||||
*/
|
||||
class JsonObjectCastException @JvmOverloads constructor(
|
||||
message: String? = null,
|
||||
throwable: Throwable? = null,
|
||||
|
||||
@@ -16,15 +16,39 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile JsonParserException.kt
|
||||
* LastUpdate 2026-10-11 16:53:41
|
||||
* LastUpdate 2026-11-17 16:22:52
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.exception
|
||||
|
||||
/**
|
||||
* 表示 JSON 解析过程中发生的异常。
|
||||
*
|
||||
* @param message 异常信息,默认为 null
|
||||
* @param throwable 异常原因,默认为 null
|
||||
* @param enableSuppression 是否启用异常抑制,默认为 false
|
||||
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
|
||||
*/
|
||||
class JsonParserException @JvmOverloads constructor(
|
||||
message: String? = null,
|
||||
throwable: Throwable? = null,
|
||||
enableSuppression: Boolean = false,
|
||||
writableStackTrace: Boolean = true,
|
||||
) : 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
|
||||
|
||||
/**
|
||||
* 表示 JSON 数据类型不匹配时抛出的异常。
|
||||
*
|
||||
* @param message 异常信息,默认为 null
|
||||
* @param throwable 异常原因,默认为 null
|
||||
* @param enableSuppression 是否启用异常抑制,默认为 false
|
||||
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
|
||||
*/
|
||||
class JsonTypeException @JvmOverloads constructor(
|
||||
message: String? = null,
|
||||
throwable: Throwable? = null,
|
||||
|
||||
@@ -22,6 +22,14 @@
|
||||
|
||||
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(
|
||||
message: String? = null,
|
||||
cause: Throwable? = null,
|
||||
|
||||
@@ -22,6 +22,14 @@
|
||||
|
||||
package com.mingliqiye.utils.exception
|
||||
|
||||
/**
|
||||
* 表示请求的资源未找到时抛出的异常。
|
||||
*
|
||||
* @param message 异常信息,默认为 null
|
||||
* @param throwable 异常原因,默认为 null
|
||||
* @param enableSuppression 是否启用异常抑制,默认为 false
|
||||
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
|
||||
*/
|
||||
class NotFoundResourceException @JvmOverloads constructor(
|
||||
message: String? = null,
|
||||
throwable: Throwable? = null,
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile FileUtils.kt
|
||||
* LastUpdate 2026-01-28 10:49:14
|
||||
* LastUpdate 2026-10-28 22:40:34
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
@file:JvmName("FileUtils")
|
||||
@@ -627,7 +627,9 @@ fun File.writeLines(lines: List<String>) {
|
||||
*/
|
||||
fun File.writeLines(lines: List<String>, charset: Charset) {
|
||||
this.parentFile?.mkdirs()
|
||||
this.writeLines(lines, charset)
|
||||
for (line in lines) {
|
||||
this.writeText(line + System.lineSeparator(), charset)
|
||||
}
|
||||
}
|
||||
|
||||
// 复制文件
|
||||
|
||||
@@ -35,7 +35,7 @@ import com.mingliqiye.utils.functions.*
|
||||
* @param <T> 可迭代对象中元素的类型
|
||||
*/
|
||||
fun <T> forEach(
|
||||
iterable: Iterable<T>, action: P2Function<in T, in Int>
|
||||
iterable: Iterable<T>, action: P2Function<in T, in Int>,
|
||||
) {
|
||||
when (iterable) {
|
||||
is RandomAccess if iterable is MutableList<*> -> {
|
||||
@@ -74,7 +74,7 @@ fun <T> forEach(
|
||||
* @param <T> 可迭代对象中元素的类型
|
||||
*/
|
||||
fun <T> forEach(
|
||||
iterable: Iterable<T>, action: P1Function<in T>
|
||||
iterable: Iterable<T>, action: P1Function<in T>,
|
||||
) {
|
||||
if (iterable is RandomAccess) {
|
||||
// 如果是支持随机访问的列表,则使用索引遍历以提高性能
|
||||
@@ -100,7 +100,7 @@ fun <T> forEach(
|
||||
* @param <T> 可迭代对象中元素的类型
|
||||
*/
|
||||
fun <T> forEachB(
|
||||
iterable: Iterable<T>, action: P2RFunction<in T, in Int, out Boolean>
|
||||
iterable: Iterable<T>, action: P2RFunction<in T, in Int, out Boolean>,
|
||||
) {
|
||||
when (iterable) {
|
||||
is RandomAccess if iterable is MutableList<*> -> {
|
||||
@@ -142,7 +142,7 @@ fun <T> forEachB(
|
||||
* @param <T> 可迭代对象中元素的类型
|
||||
*/
|
||||
fun <T> forEachB(
|
||||
iterable: Iterable<T>, action: P1RFunction<in T, out Boolean>
|
||||
iterable: Iterable<T>, action: P1RFunction<in T, out Boolean>,
|
||||
) {
|
||||
if (iterable is RandomAccess) {
|
||||
// 如果是支持随机访问的列表,则使用索引遍历以提高性能
|
||||
@@ -166,7 +166,7 @@ fun <T> forEachB(
|
||||
* @param <T> 数组中元素的类型
|
||||
*/
|
||||
fun <T> forEach(
|
||||
array: Array<T>, action: P2Function<in T, in Int>
|
||||
array: Array<T>, action: P2Function<in T, in Int>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -179,7 +179,7 @@ fun <T> forEach(
|
||||
* @param <T> 数组中元素的类型
|
||||
*/
|
||||
fun <T> forEach(
|
||||
array: Array<T>, action: P1Function<in T>
|
||||
array: Array<T>, action: P1Function<in T>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -193,7 +193,7 @@ fun <T> forEach(
|
||||
* @param <T> 数组中元素的类型
|
||||
*/
|
||||
fun <T> forEachB(
|
||||
array: Array<T>, action: P2RFunction<in T, in Int, out Boolean>
|
||||
array: Array<T>, action: P2RFunction<in T, in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -207,7 +207,7 @@ fun <T> forEachB(
|
||||
* @param <T> 数组中元素的类型
|
||||
*/
|
||||
fun <T> forEachB(
|
||||
array: Array<T>, action: P1RFunction<in T, out Boolean>
|
||||
array: Array<T>, action: P1RFunction<in T, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -219,7 +219,7 @@ fun <T> forEachB(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: ByteArray, action: P2Function<in Byte, in Int>
|
||||
array: ByteArray, action: P2Function<in Byte, in Int>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -231,7 +231,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: ByteArray, action: P1Function<in Byte>
|
||||
array: ByteArray, action: P1Function<in Byte>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -244,7 +244,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: ByteArray, action: P2RFunction<in Byte, in Int, out Boolean>
|
||||
array: ByteArray, action: P2RFunction<in Byte, in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -257,7 +257,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: ByteArray, action: P1RFunction<in Byte, out Boolean>
|
||||
array: ByteArray, action: P1RFunction<in Byte, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -269,7 +269,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: CharArray, action: P2Function<in Char, in Int>
|
||||
array: CharArray, action: P2Function<in Char, in Int>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -281,7 +281,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: CharArray, action: P1Function<in Char>
|
||||
array: CharArray, action: P1Function<in Char>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -294,7 +294,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: CharArray, action: P2RFunction<in Char, in Int, out Boolean>
|
||||
array: CharArray, action: P2RFunction<in Char, in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -307,7 +307,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: CharArray, action: P1RFunction<in Char, out Boolean>
|
||||
array: CharArray, action: P1RFunction<in Char, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -319,7 +319,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: IntArray, action: P2Function<in Int, in Int>
|
||||
array: IntArray, action: P2Function<in Int, in Int>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -331,7 +331,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: IntArray, action: P1Function<in Int>
|
||||
array: IntArray, action: P1Function<in Int>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -344,7 +344,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: IntArray, action: P2RFunction<in Int, in Int, out Boolean>
|
||||
array: IntArray, action: P2RFunction<in Int, in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -357,7 +357,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: IntArray, action: P1RFunction<in Int, out Boolean>
|
||||
array: IntArray, action: P1RFunction<in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -369,7 +369,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: LongArray, action: P2Function<in Long, in Int>
|
||||
array: LongArray, action: P2Function<in Long, in Int>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -381,7 +381,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: LongArray, action: P1Function<in Long>
|
||||
array: LongArray, action: P1Function<in Long>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -394,7 +394,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: LongArray, action: P2RFunction<in Long, in Int, out Boolean>
|
||||
array: LongArray, action: P2RFunction<in Long, in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -407,7 +407,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: LongArray, action: P1RFunction<in Long, out Boolean>
|
||||
array: LongArray, action: P1RFunction<in Long, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -419,7 +419,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: ShortArray, action: P2Function<in Short, in Int>
|
||||
array: ShortArray, action: P2Function<in Short, in Int>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -431,7 +431,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: ShortArray, action: P1Function<in Short>
|
||||
array: ShortArray, action: P1Function<in Short>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -444,7 +444,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: ShortArray, action: P2RFunction<in Short, in Int, out Boolean>
|
||||
array: ShortArray, action: P2RFunction<in Short, in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -457,7 +457,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: ShortArray, action: P1RFunction<in Short, out Boolean>
|
||||
array: ShortArray, action: P1RFunction<in Short, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -469,7 +469,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: FloatArray, action: P2Function<in Float, in Int>
|
||||
array: FloatArray, action: P2Function<in Float, in Int>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -481,7 +481,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: FloatArray, action: P1Function<in Float>
|
||||
array: FloatArray, action: P1Function<in Float>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -494,7 +494,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: FloatArray, action: P2RFunction<in Float, in Int, out Boolean>
|
||||
array: FloatArray, action: P2RFunction<in Float, in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -507,7 +507,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: FloatArray, action: P1RFunction<in Float, out Boolean>
|
||||
array: FloatArray, action: P1RFunction<in Float, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -519,7 +519,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: DoubleArray, action: P2Function<in Double, in Int>
|
||||
array: DoubleArray, action: P2Function<in Double, in Int>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -531,7 +531,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: DoubleArray, action: P1Function<in Double>
|
||||
array: DoubleArray, action: P1Function<in Double>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -544,7 +544,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: DoubleArray, action: P2RFunction<in Double, in Int, out Boolean>
|
||||
array: DoubleArray, action: P2RFunction<in Double, in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -557,7 +557,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: DoubleArray, action: P1RFunction<in Double, out Boolean>
|
||||
array: DoubleArray, action: P1RFunction<in Double, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -569,7 +569,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: BooleanArray, action: P2Function<in Boolean, in Int>
|
||||
array: BooleanArray, action: P2Function<in Boolean, in Int>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -581,7 +581,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
||||
*/
|
||||
fun forEach(
|
||||
array: BooleanArray, action: P1Function<in Boolean>
|
||||
array: BooleanArray, action: P1Function<in Boolean>,
|
||||
) {
|
||||
forEach(array.toList(), action)
|
||||
}
|
||||
@@ -594,7 +594,7 @@ fun forEach(
|
||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: BooleanArray, action: P2RFunction<in Boolean, in Int, out Boolean>
|
||||
array: BooleanArray, action: P2RFunction<in Boolean, in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -607,7 +607,7 @@ fun forEachB(
|
||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
||||
*/
|
||||
fun forEachB(
|
||||
array: BooleanArray, action: P1RFunction<in Boolean, out Boolean>
|
||||
array: BooleanArray, action: P1RFunction<in Boolean, out Boolean>,
|
||||
) {
|
||||
forEachB(array.toList(), action)
|
||||
}
|
||||
@@ -623,7 +623,7 @@ fun forEachB(
|
||||
* @param <A> 集合的具体类型
|
||||
*/
|
||||
fun <K, V, A : Collection<Map.Entry<K, V>>> forEachB(
|
||||
array: A, action: P3RFunction<in K, in V, in Int, out Boolean>
|
||||
array: A, action: P3RFunction<in K, in V, in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(array, P2RFunction<Map.Entry<K, V>, Int, Boolean> { p1, p2 -> action.call(p1.key, p1.value, p2) })
|
||||
}
|
||||
@@ -639,7 +639,7 @@ fun <K, V, A : Collection<Map.Entry<K, V>>> forEachB(
|
||||
* @param <A> 映射的具体类型
|
||||
*/
|
||||
fun <K, V, A : Map<K, V>> forEachB(
|
||||
map: A, action: P3RFunction<in K, in V, in Int, out Boolean>
|
||||
map: A, action: P3RFunction<in K, in V, in Int, out Boolean>,
|
||||
) {
|
||||
forEachB(map.entries, P2RFunction<Map.Entry<K, V>, Int, Boolean> { p1, p2 -> action.call(p1.key, p1.value, p2) })
|
||||
}
|
||||
@@ -654,7 +654,7 @@ fun <K, V, A : Map<K, V>> forEachB(
|
||||
* @param <A> 集合的具体类型
|
||||
*/
|
||||
fun <K, V, A : Collection<Map.Entry<K, V>>> forEachMap(
|
||||
array: A, action: P2Function<in K, in V>
|
||||
array: A, action: P2Function<in K, in V>,
|
||||
) {
|
||||
forEach(array, P1Function<Map.Entry<K, V>> { p1 -> action.call(p1.key, p1.value) })
|
||||
}
|
||||
@@ -669,7 +669,7 @@ fun <K, V, A : Collection<Map.Entry<K, V>>> forEachMap(
|
||||
* @param <A> 映射的具体类型
|
||||
*/
|
||||
fun <K, V, A : Map<K, V>> forEachMap(
|
||||
map: A, action: P2Function<in K, in V>
|
||||
map: A, action: P2Function<in K, in V>,
|
||||
) {
|
||||
forEach(map.entries, P1Function<Map.Entry<K, V>> { p1 -> action.call(p1.key, p1.value) })
|
||||
}
|
||||
@@ -685,7 +685,7 @@ fun <K, V, A : Map<K, V>> forEachMap(
|
||||
* @param <A> 集合的具体类型
|
||||
*/
|
||||
fun <K, V, A : Collection<Map.Entry<K, V>>> forEachMapB(
|
||||
array: A, action: P2RFunction<in K, in V, out Boolean>
|
||||
array: A, action: P2RFunction<in K, in V, out Boolean>,
|
||||
) {
|
||||
forEachB(array, P1RFunction<Map.Entry<K, V>, Boolean> { p1 -> action.call(p1.key, p1.value) })
|
||||
}
|
||||
@@ -701,7 +701,7 @@ fun <K, V, A : Collection<Map.Entry<K, V>>> forEachMapB(
|
||||
* @param <A> 映射的具体类型
|
||||
*/
|
||||
fun <K, V, A : Map<K, V>> forEachMapB(
|
||||
map: A, action: P2RFunction<in K, in V, out Boolean>
|
||||
map: A, action: P2RFunction<in K, in V, out Boolean>,
|
||||
) {
|
||||
forEachB(map.entries, P1RFunction<Map.Entry<K, V>, Boolean> { p1 -> action.call(p1.key, p1.value) })
|
||||
}
|
||||
|
||||
@@ -24,151 +24,381 @@
|
||||
|
||||
package com.mingliqiye.utils.functions
|
||||
|
||||
/**
|
||||
* 对任意对象执行无参函数调用,执行完成后返回接收者自身。
|
||||
*
|
||||
* @param function 要执行的无参函数
|
||||
* @return 接收者自身
|
||||
*/
|
||||
fun <T> T.with(function: Function): T = function.call().let {
|
||||
this
|
||||
}
|
||||
|
||||
/**
|
||||
* 以接收者自身作为参数执行函数调用,执行完成后返回接收者自身。
|
||||
*
|
||||
* @param function 接收一个参数的函数,调用时传入接收者自身
|
||||
* @return 接收者自身
|
||||
*/
|
||||
fun <T> T.with(function: P1Function<T>): T = function.call(this).let {
|
||||
this
|
||||
}
|
||||
|
||||
/**
|
||||
* 无参数且无返回值的函数式接口。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface Function {
|
||||
/**
|
||||
* 执行函数调用。
|
||||
*/
|
||||
fun call()
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 1 个参数且无返回值的函数式接口。
|
||||
*
|
||||
* @param P 参数类型
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P1Function<P> {
|
||||
/**
|
||||
* 执行函数调用。
|
||||
*
|
||||
* @param p 参数
|
||||
*/
|
||||
fun call(p: P)
|
||||
}
|
||||
|
||||
/**
|
||||
* 无参数且带返回值的函数式接口。
|
||||
*
|
||||
* @param R 返回值类型
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface RFunction<R> {
|
||||
/**
|
||||
* 执行函数调用。
|
||||
*
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 1 个参数且带返回值的函数式接口。
|
||||
*
|
||||
* @param P 参数类型
|
||||
* @param R 返回值类型
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P1RFunction<P, R> {
|
||||
/**
|
||||
* 执行函数调用。
|
||||
*
|
||||
* @param p 参数
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(p: P): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 2 个参数且无返回值的函数式接口。
|
||||
*
|
||||
* @param P 第 1 个参数类型
|
||||
* @param P1 第 2 个参数类型
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P2Function<P, P1> {
|
||||
/**
|
||||
* 执行函数调用。
|
||||
*
|
||||
* @param p 第 1 个参数
|
||||
* @param p1 第 2 个参数
|
||||
*/
|
||||
fun call(p: P, p1: P1)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 2 个参数且带返回值的函数式接口。
|
||||
*
|
||||
* @param P 第 1 个参数类型
|
||||
* @param P1 第 2 个参数类型
|
||||
* @param R 返回值类型
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P2RFunction<P, P1, R> {
|
||||
/**
|
||||
* 执行函数调用。
|
||||
*
|
||||
* @param p 第 1 个参数
|
||||
* @param p1 第 2 个参数
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(p: P, p1: P1): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 3 个参数且无返回值的函数式接口,参数类型依次为 P、P1、P2。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P3Function<P, P1, P2> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1、p2。
|
||||
*/
|
||||
fun call(p: P, p1: P1, p2: P2)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 3 个参数且带返回值的函数式接口,参数类型依次为 P、P1、P2,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P3RFunction<P, P1, P2, R> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1、p2。
|
||||
*
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(p: P, p1: P1, p2: P2): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 4 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P3。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P4Function<P, P1, P2, P3> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p3。
|
||||
*/
|
||||
fun call(p: P, p1: P1, p2: P2, p3: P3)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 4 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P3,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P4RFunction<P, P1, P2, P3, R> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p3。
|
||||
*
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(p: P, p1: P1, p2: P2, p3: P3): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 5 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P4。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P5Function<P, P1, P2, P3, P4> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p4。
|
||||
*/
|
||||
fun call(p: P, p1: P1, p2: P2, p3: P3, p4: P4)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 5 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P4,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 6 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P5。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 6 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P5,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 7 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P6。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 7 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P6,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 8 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P7。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 8 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P7,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 9 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P8。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 9 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P8,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 10 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P9。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 10 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P9,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 11 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P10。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 11 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P10,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 12 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P11。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 12 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P11,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 13 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P12。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 13 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P12,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P13RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p12。
|
||||
*
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -182,12 +412,18 @@ fun interface P13RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p9: P9,
|
||||
p10: P10,
|
||||
p11: P11,
|
||||
p12: P12
|
||||
p12: P12,
|
||||
): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 14 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P13。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P14Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p13。
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -202,12 +438,20 @@ fun interface P14Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p10: P10,
|
||||
p11: P11,
|
||||
p12: P12,
|
||||
p13: P13
|
||||
p13: P13,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 14 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P13,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P14RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p13。
|
||||
*
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -222,12 +466,18 @@ fun interface P14RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p10: P10,
|
||||
p11: P11,
|
||||
p12: P12,
|
||||
p13: P13
|
||||
p13: P13,
|
||||
): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 15 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P14。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P15Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p14。
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -243,12 +493,20 @@ fun interface P15Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p11: P11,
|
||||
p12: P12,
|
||||
p13: P13,
|
||||
p14: P14
|
||||
p14: P14,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 15 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P14,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -264,12 +522,18 @@ fun interface P15RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p11: P11,
|
||||
p12: P12,
|
||||
p13: P13,
|
||||
p14: P14
|
||||
p14: P14,
|
||||
): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 16 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P15。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
fun interface P16Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p15。
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -286,12 +550,20 @@ fun interface P16Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p12: P12,
|
||||
p13: P13,
|
||||
p14: P14,
|
||||
p15: P15
|
||||
p15: P15,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 16 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P15,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -308,12 +580,18 @@ fun interface P16RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p12: P12,
|
||||
p13: P13,
|
||||
p14: P14,
|
||||
p15: P15
|
||||
p15: P15,
|
||||
): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 17 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P16。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -331,12 +609,20 @@ fun interface P17Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p13: P13,
|
||||
p14: P14,
|
||||
p15: P15,
|
||||
p16: P16
|
||||
p16: P16,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 17 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P16,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -354,12 +640,18 @@ fun interface P17RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p13: P13,
|
||||
p14: P14,
|
||||
p15: P15,
|
||||
p16: P16
|
||||
p16: P16,
|
||||
): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 18 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P17。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -378,12 +670,20 @@ fun interface P18Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p14: P14,
|
||||
p15: P15,
|
||||
p16: P16,
|
||||
p17: P17
|
||||
p17: P17,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 18 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P17,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -402,12 +702,18 @@ fun interface P18RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p14: P14,
|
||||
p15: P15,
|
||||
p16: P16,
|
||||
p17: P17
|
||||
p17: P17,
|
||||
): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 19 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P18。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -427,12 +733,20 @@ fun interface P19Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p15: P15,
|
||||
p16: P16,
|
||||
p17: P17,
|
||||
p18: P18
|
||||
p18: P18,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 19 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P18,返回值类型为 R。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -452,12 +766,18 @@ fun interface P19RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p15: P15,
|
||||
p16: P16,
|
||||
p17: P17,
|
||||
p18: P18
|
||||
p18: P18,
|
||||
): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 20 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P19。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
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(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -478,12 +798,20 @@ fun interface P20Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p16: P16,
|
||||
p17: P17,
|
||||
p18: P18,
|
||||
p19: P19
|
||||
p19: P19,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 20 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P19,返回值类型为 R。
|
||||
*/
|
||||
@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> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p19。
|
||||
*
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -504,12 +832,18 @@ fun interface P20RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p16: P16,
|
||||
p17: P17,
|
||||
p18: P18,
|
||||
p19: P19
|
||||
p19: P19,
|
||||
): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 21 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P20。
|
||||
*/
|
||||
@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> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p20。
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -531,12 +865,20 @@ fun interface P21Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p17: P17,
|
||||
p18: P18,
|
||||
p19: P19,
|
||||
p20: P20
|
||||
p20: P20,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 21 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P20,返回值类型为 R。
|
||||
*/
|
||||
@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> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p20。
|
||||
*
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -558,12 +900,18 @@ fun interface P21RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p17: P17,
|
||||
p18: P18,
|
||||
p19: P19,
|
||||
p20: P20
|
||||
p20: P20,
|
||||
): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 22 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P21。
|
||||
*/
|
||||
@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> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p21。
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -586,12 +934,20 @@ fun interface P22Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p18: P18,
|
||||
p19: P19,
|
||||
p20: P20,
|
||||
p21: P21
|
||||
p21: P21,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 22 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P21,返回值类型为 R。
|
||||
*/
|
||||
@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> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p21。
|
||||
*
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -614,12 +970,18 @@ fun interface P22RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p18: P18,
|
||||
p19: P19,
|
||||
p20: P20,
|
||||
p21: P21
|
||||
p21: P21,
|
||||
): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 23 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P22。
|
||||
*/
|
||||
@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> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p22。
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -643,41 +1005,20 @@ fun interface P23Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p19: P19,
|
||||
p20: P20,
|
||||
p21: P21,
|
||||
p22: P22
|
||||
p22: P22,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 23 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P22,返回值类型为 R。
|
||||
*/
|
||||
@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 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,
|
||||
p13: P13,
|
||||
p14: P14,
|
||||
p15: P15,
|
||||
p16: P16,
|
||||
p17: P17,
|
||||
p18: P18,
|
||||
p19: P19,
|
||||
p20: P20,
|
||||
p21: P21,
|
||||
p22: P22
|
||||
): R
|
||||
}
|
||||
|
||||
@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> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p22。
|
||||
*
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -702,12 +1043,55 @@ fun interface P24Function<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p20: P20,
|
||||
p21: P21,
|
||||
p22: P22,
|
||||
p23: P23
|
||||
): R
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 24 个参数且无返回值的函数式接口,参数类型依次为 P、P1 至 P23。
|
||||
*/
|
||||
@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> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p23。
|
||||
*/
|
||||
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,
|
||||
p13: P13,
|
||||
p14: P14,
|
||||
p15: P15,
|
||||
p16: P16,
|
||||
p17: P17,
|
||||
p18: P18,
|
||||
p19: P19,
|
||||
p20: P20,
|
||||
p21: P21,
|
||||
p22: P22,
|
||||
p23: P23,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 24 个参数且带返回值的函数式接口,参数类型依次为 P、P1 至 P23,返回值类型为 R。
|
||||
*/
|
||||
@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> {
|
||||
/**
|
||||
* 执行函数调用,参数依次为 p、p1 至 p23。
|
||||
*
|
||||
* @return 函数执行结果
|
||||
*/
|
||||
fun call(
|
||||
p: P,
|
||||
p1: P1,
|
||||
@@ -732,6 +1116,6 @@ fun interface P24RFunction<P, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12,
|
||||
p20: P20,
|
||||
p21: P21,
|
||||
p22: P22,
|
||||
p23: P23
|
||||
p23: P23,
|
||||
): R
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* 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 HashType.kt
|
||||
* LastUpdate 2026-11-18 18:48:01
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash
|
||||
|
||||
import com.mingliqiye.utils.hash.code.HashCodec
|
||||
import java.io.InputStream
|
||||
|
||||
/**
|
||||
* 哈希算法类型枚举。
|
||||
*
|
||||
* 每个枚举项持有一个哈希编解码器的工厂函数,枚举本身实现了 [HashCodec],
|
||||
* 可直接作为编解码器使用,哈希操作委托给对应的编解码器实例。
|
||||
*
|
||||
* @param codec 哈希编解码器的工厂函数,每次访问 [code] 时调用以创建实例
|
||||
*/
|
||||
enum class HashType(private val codec: () -> HashCodec) : HashCodec {
|
||||
/** MD2 哈希(输出 128 位,已过时,仅用于兼容遗留系统)。 */
|
||||
MD2(::MD2),
|
||||
/** MD5 哈希(输出 128 位,存在碰撞漏洞,不得用于安全场景)。 */
|
||||
MD5(::MD5),
|
||||
/** SHA-1 哈希(输出 160 位,存在碰撞攻击,不得用于安全场景)。 */
|
||||
SHA1(::SHA1),
|
||||
/** SHA-224 哈希(SHA-2 家族,输出 224 位)。 */
|
||||
SHA224(::SHA224),
|
||||
/** SHA-256 哈希(SHA-2 家族,输出 256 位)。 */
|
||||
SHA256(::SHA256),
|
||||
/** SHA-384 哈希(SHA-2 家族,输出 384 位)。 */
|
||||
SHA384(::SHA384),
|
||||
/** SHA-512 哈希(SHA-2 家族,输出 512 位)。 */
|
||||
SHA512(::SHA512),
|
||||
/** SHA3-224 哈希(SHA-3 家族,输出 224 位)。 */
|
||||
SHA3224(::SHA3224),
|
||||
/** SHA3-256 哈希(SHA-3 家族,输出 256 位)。 */
|
||||
SHA3256(::SHA3256),
|
||||
/** SHA3-384 哈希(SHA-3 家族,输出 384 位)。 */
|
||||
SHA3384(::SHA3384),
|
||||
/** SHA3-512 哈希(SHA-3 家族,输出 512 位)。 */
|
||||
SHA3512(::SHA3512),
|
||||
/** SHA-512/224 哈希(SHA-2 家族,输出 224 位)。 */
|
||||
SHA512224(::SHA512224),
|
||||
/** SHA-512/256 哈希(SHA-2 家族,输出 256 位)。 */
|
||||
SHA512256(::SHA512256);
|
||||
|
||||
|
||||
/**
|
||||
* 获取当前类型对应的哈希编解码器实例(每次访问都会通过工厂函数新建)。
|
||||
*/
|
||||
val code get() = codec()
|
||||
|
||||
/**
|
||||
* 计算输入流内容的哈希值,委托给 [code] 对应的编解码器。
|
||||
*
|
||||
* @param input 待计算哈希的输入流
|
||||
* @return 哈希结果字节数组
|
||||
*/
|
||||
override fun hash(input: InputStream): ByteArray {
|
||||
return code.hash(input)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -16,71 +16,103 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile HashUtils.kt
|
||||
* LastUpdate 2026-01-11 09:09:52
|
||||
* LastUpdate 2026-11-18 18:53:11
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
@file:JvmName("HashUtils")
|
||||
|
||||
package com.mingliqiye.utils.hash
|
||||
|
||||
import com.mingliqiye.utils.hash.code.*
|
||||
|
||||
import com.mingliqiye.utils.bcrypt.checkpw
|
||||
import com.mingliqiye.utils.bcrypt.hashpw
|
||||
import com.mingliqiye.utils.bytes.bytesToHex
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.IOException
|
||||
import java.security.MessageDigest
|
||||
import java.security.NoSuchAlgorithmException
|
||||
|
||||
/**
|
||||
* 计算指定文件的哈希值。
|
||||
*
|
||||
* @param file 要计算哈希值的文件对象
|
||||
* @param algorithm 使用的哈希算法名称(如 SHA-256、MD5 等)
|
||||
* @return 文件的十六进制格式哈希值字符串
|
||||
* @throws IOException 当文件不存在或读取过程中发生 I/O 错误时抛出
|
||||
* @throws NoSuchAlgorithmException 当指定的哈希算法不可用时抛出
|
||||
* 提供 MD2 哈希器的懒加载实例。
|
||||
* 该哈希器输出 128 位摘要,算法已过时,仅用于兼容遗留系统。
|
||||
*/
|
||||
@Throws(IOException::class, NoSuchAlgorithmException::class)
|
||||
fun calculateFileHash(file: File, algorithm: String): String {
|
||||
// 检查文件是否存在
|
||||
if (!file.exists()) {
|
||||
throw IOException("File not found: " + file.absolutePath)
|
||||
}
|
||||
|
||||
val digest = MessageDigest.getInstance(algorithm)
|
||||
|
||||
FileInputStream(file).use { fis ->
|
||||
val buffer = ByteArray(8192)
|
||||
var bytesRead: Int
|
||||
|
||||
// 分块读取文件内容并更新摘要
|
||||
while (fis.read(buffer).also { bytesRead = it } != -1) {
|
||||
digest.update(buffer, 0, bytesRead)
|
||||
}
|
||||
}
|
||||
|
||||
return bytesToHex(digest.digest())
|
||||
}
|
||||
@get:JvmName("getMd2Codec")
|
||||
val MD2 by lazy(::Md2Codec)
|
||||
|
||||
/**
|
||||
* 使用 BCrypt 算法对字符串进行加密。
|
||||
*
|
||||
* @param string 需要加密的明文字符串
|
||||
* @return 加密后的 BCrypt 哈希字符串
|
||||
* 提供 MD5 哈希器的懒加载实例。
|
||||
* 该哈希器输出 128 位摘要,存在碰撞漏洞,不得用于安全场景,仅建议非安全性校验。
|
||||
*/
|
||||
fun bcrypt(string: String): String {
|
||||
return hashpw(string)
|
||||
}
|
||||
@get:JvmName("getMd5Codec")
|
||||
val MD5 by lazy(::Md5Codec)
|
||||
|
||||
/**
|
||||
* 验证给定字符串与 BCrypt 哈希是否匹配。
|
||||
*
|
||||
* @param string 明文字符串
|
||||
* @param bcrypted 已经使用 BCrypt 加密的哈希字符串
|
||||
* @return 如果匹配返回 true,否则返回 false
|
||||
* 提供 SHA-1 哈希器的懒加载实例。
|
||||
* 该哈希器输出 160 位摘要,存在碰撞攻击,不得用于安全场景,仅建议非安全性校验。
|
||||
*/
|
||||
fun checkBcrypt(string: String, bcrypted: String): Boolean {
|
||||
return checkpw(string, bcrypted)
|
||||
}
|
||||
@get:JvmName("getSha1Codec")
|
||||
val SHA1 by lazy(::Sha1Codec)
|
||||
|
||||
/**
|
||||
* 提供 SHA-224 哈希器的懒加载实例。
|
||||
* 该哈希器属于 SHA-2 家族,输出 224 位摘要。
|
||||
*/
|
||||
@get:JvmName("getSha224Codec")
|
||||
val SHA224 by lazy(::Sha224Codec)
|
||||
|
||||
/**
|
||||
* 提供 SHA-256 哈希器的懒加载实例。
|
||||
* 该哈希器属于 SHA-2 家族,输出 256 位摘要,适用于文件校验、数字签名等场景。
|
||||
*/
|
||||
@get:JvmName("getSha256Codec")
|
||||
val SHA256 by lazy(::Sha256Codec)
|
||||
|
||||
/**
|
||||
* 提供 SHA-384 哈希器的懒加载实例。
|
||||
* 该哈希器属于 SHA-2 家族,输出 384 位摘要。
|
||||
*/
|
||||
@get:JvmName("getSha384Codec")
|
||||
val SHA384 by lazy(::Sha384Codec)
|
||||
|
||||
/**
|
||||
* 提供 SHA-512 哈希器的懒加载实例。
|
||||
* 该哈希器属于 SHA-2 家族,输出 512 位摘要,在 64 位平台上通常比 SHA-256 更快。
|
||||
*/
|
||||
@get:JvmName("getSha512Codec")
|
||||
val SHA512 by lazy(::Sha512Codec)
|
||||
|
||||
/**
|
||||
* 提供 SHA3-224 哈希器的懒加载实例。
|
||||
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 224 位摘要。
|
||||
*/
|
||||
@get:JvmName("getSha3224Codec")
|
||||
val SHA3224 by lazy(::Sha3224Codec)
|
||||
|
||||
/**
|
||||
* 提供 SHA3-256 哈希器的懒加载实例。
|
||||
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 256 位摘要。
|
||||
*/
|
||||
@get:JvmName("getSha3256Codec")
|
||||
val SHA3256 by lazy(::Sha3256Codec)
|
||||
|
||||
/**
|
||||
* 提供 SHA3-384 哈希器的懒加载实例。
|
||||
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 384 位摘要。
|
||||
*/
|
||||
@get:JvmName("getSha3384Codec")
|
||||
val SHA3384 by lazy(::Sha3384Codec)
|
||||
|
||||
/**
|
||||
* 提供 SHA3-512 哈希器的懒加载实例。
|
||||
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 512 位摘要。
|
||||
*/
|
||||
@get:JvmName("getSha3512Codec")
|
||||
val SHA3512 by lazy(::Sha3512Codec)
|
||||
|
||||
/**
|
||||
* 提供 SHA-512/224 哈希器的懒加载实例。
|
||||
* 该哈希器以 SHA-512 的运算结构截断输出至 224 位,在 64 位平台上性能优于 SHA-224。
|
||||
*/
|
||||
@get:JvmName("getSha512224Codec")
|
||||
val SHA512224 by lazy(::Sha512224Codec)
|
||||
|
||||
/**
|
||||
* 提供 SHA-512/256 哈希器的懒加载实例。
|
||||
* 该哈希器以 SHA-512 的运算结构截断输出至 256 位,在 64 位平台上性能优于 SHA-256。
|
||||
*/
|
||||
@get:JvmName("getSha512256Codec")
|
||||
val SHA512256 by lazy(::Sha512256Codec)
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
/*
|
||||
* 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 HashCodec.kt
|
||||
* LastUpdate 2026-11-18 18:36:00
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
import com.mingliqiye.utils.base.BaseType
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.nio.charset.Charset
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* 哈希编解码器接口。
|
||||
*
|
||||
* 实现类只需重写 [hash](InputStream 版本)一个方法,
|
||||
* 其余字节数组、字符串、文件、路径的重载以及十六进制输出、
|
||||
* 哈希校验均由接口提供默认实现。
|
||||
*
|
||||
* 使用示例(以 SHA-256 为例):
|
||||
* ```
|
||||
* val sha256 = Sha256Codec()
|
||||
* val hex = sha256.hashHex("hello")
|
||||
* val ok = sha256.verifyHash("hello", hex)
|
||||
* ```
|
||||
*/
|
||||
interface HashCodec {
|
||||
|
||||
/**
|
||||
* 计算输入流内容的哈希值(唯一需要实现的方法)。
|
||||
*
|
||||
* 实现不需要关闭输入流,由调用方负责流的生命周期。
|
||||
*
|
||||
* @param input 待计算哈希的输入流
|
||||
* @return 哈希结果字节数组
|
||||
*/
|
||||
fun hash(input: InputStream): ByteArray
|
||||
|
||||
/**
|
||||
* 计算字节数组的哈希值。
|
||||
*
|
||||
* @param bytes 待计算哈希的字节数组
|
||||
* @return 哈希结果字节数组
|
||||
*/
|
||||
fun hash(bytes: ByteArray): ByteArray = hash(bytes.inputStream())
|
||||
|
||||
/**
|
||||
* 计算字符串的哈希值。
|
||||
*
|
||||
* @param string 待计算哈希的字符串
|
||||
* @param charset 字符串编码字符集,默认 UTF-8
|
||||
* @return 哈希结果字节数组
|
||||
*/
|
||||
fun hash(string: String, charset: Charset = Charsets.UTF_8): ByteArray = hash(string.toByteArray(charset))
|
||||
|
||||
/**
|
||||
* 计算文件内容的哈希值。
|
||||
*
|
||||
* @param file 待计算哈希的文件
|
||||
* @return 哈希结果字节数组
|
||||
*/
|
||||
fun hash(file: File): ByteArray = file.inputStream().use { hash(it) }
|
||||
|
||||
/**
|
||||
* 计算路径指向文件内容的哈希值。
|
||||
*
|
||||
* @param path 待计算哈希的文件路径
|
||||
* @return 哈希结果字节数组
|
||||
*/
|
||||
fun hash(path: Path): ByteArray = Files.newInputStream(path).use { hash(it) }
|
||||
|
||||
/**
|
||||
* 计算输入流内容的哈希值并以小写十六进制字符串返回。
|
||||
*
|
||||
* @param input 待计算哈希的输入流
|
||||
* @return 十六进制格式的哈希字符串
|
||||
*/
|
||||
fun hashHex(input: InputStream): String = BaseType.BASE16.encode(hash(input))
|
||||
|
||||
/**
|
||||
* 计算字节数组的哈希值并以小写十六进制字符串返回。
|
||||
*
|
||||
* @param bytes 待计算哈希的字节数组
|
||||
* @return 十六进制格式的哈希字符串
|
||||
*/
|
||||
fun hashHex(bytes: ByteArray): String = BaseType.BASE16.encode(hash(bytes))
|
||||
|
||||
/**
|
||||
* 计算字符串的哈希值并以小写十六进制字符串返回。
|
||||
*
|
||||
* @param string 待计算哈希的字符串
|
||||
* @param charset 字符串编码字符集,默认 UTF-8
|
||||
* @return 十六进制格式的哈希字符串
|
||||
*/
|
||||
fun hashHex(string: String, charset: Charset = Charsets.UTF_8): String =
|
||||
BaseType.BASE16.encode(hash(string, charset))
|
||||
|
||||
/**
|
||||
* 计算文件内容的哈希值并以小写十六进制字符串返回。
|
||||
*
|
||||
* @param file 待计算哈希的文件
|
||||
* @return 十六进制格式的哈希字符串
|
||||
*/
|
||||
fun hashHex(file: File): String = BaseType.BASE16.encode(hash(file))
|
||||
|
||||
/**
|
||||
* 计算路径指向文件内容的哈希值并以小写十六进制字符串返回。
|
||||
*
|
||||
* @param path 待计算哈希的文件路径
|
||||
* @return 十六进制格式的哈希字符串
|
||||
*/
|
||||
fun hashHex(path: Path): String = BaseType.BASE16.encode(hash(path))
|
||||
|
||||
/**
|
||||
* 校验输入流内容的哈希值是否与期望值一致。
|
||||
*
|
||||
* 使用 [java.security.MessageDigest.isEqual] 进行常量时间比较,避免时序攻击。
|
||||
*
|
||||
* @param input 待校验的输入流
|
||||
* @param hashed 期望的哈希值字节数组
|
||||
* @return 一致返回 true,否则返回 false
|
||||
*/
|
||||
fun verifyHash(input: InputStream, hashed: ByteArray): Boolean = MessageDigest.isEqual(hash(input), hashed)
|
||||
|
||||
/**
|
||||
* 校验字节数组的哈希值是否与期望值一致。
|
||||
*
|
||||
* @param bytes 待校验的字节数组
|
||||
* @param hashed 期望的哈希值字节数组
|
||||
* @return 一致返回 true,否则返回 false
|
||||
*/
|
||||
fun verifyHash(bytes: ByteArray, hashed: ByteArray): Boolean = MessageDigest.isEqual(hash(bytes), hashed)
|
||||
|
||||
/**
|
||||
* 校验字符串的哈希值是否与期望值一致。
|
||||
*
|
||||
* @param string 待校验的字符串
|
||||
* @param hashed 期望的哈希值字节数组
|
||||
* @param charset 字符串编码字符集,默认 UTF-8
|
||||
* @return 一致返回 true,否则返回 false
|
||||
*/
|
||||
fun verifyHash(string: String, hashed: ByteArray, charset: Charset = Charsets.UTF_8): Boolean =
|
||||
MessageDigest.isEqual(hash(string, charset), hashed)
|
||||
|
||||
/**
|
||||
* 校验字符串的哈希值是否与期望的十六进制字符串一致(忽略大小写)。
|
||||
*
|
||||
* @param string 待校验的字符串
|
||||
* @param hashedHex 期望的十六进制哈希字符串
|
||||
* @param charset 字符串编码字符集,默认 UTF-8
|
||||
* @return 一致返回 true,否则返回 false
|
||||
*/
|
||||
fun verifyHash(string: String, hashedHex: String, charset: Charset = Charsets.UTF_8): Boolean =
|
||||
MessageDigest.isEqual(hash(string, charset), BaseType.BASE16.decode(hashedHex.lowercase()))
|
||||
|
||||
}
|
||||
+9
-12
@@ -15,19 +15,16 @@
|
||||
*
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile ApplicationRunnerData.kt
|
||||
* LastUpdate 2026-03-10 09:10:50
|
||||
* CurrentFile Md2Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.springboot.listener
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
import java.lang.reflect.Method
|
||||
|
||||
data class ApplicationRunnerData(
|
||||
val beanName: String, val order: Int, val bean: Any, val method: Method
|
||||
) {
|
||||
fun run() {
|
||||
method.invoke(bean)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* MD2 哈希编解码器(输出 128 位 / 16 字节)。
|
||||
*
|
||||
* MD2 已过时且存在安全缺陷,仅用于兼容遗留系统,不建议在任何新场景使用。
|
||||
*/
|
||||
class Md2Codec : MessageDigestCodec("MD2")
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* 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 Md5Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* MD5 哈希编解码器(输出 128 位 / 16 字节)。
|
||||
*
|
||||
* MD5 已被证实存在碰撞漏洞,不得用于数字签名、密码存储等安全场景,
|
||||
* 仅建议用于兼容遗留系统或非安全性校验(如文件完整性粗检)。
|
||||
*/
|
||||
class Md5Codec : MessageDigestCodec("MD5")
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* 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 MessageDigestCodec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
import java.io.InputStream
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* 基于 JDK [MessageDigest] 的哈希编解码器抽象基类。
|
||||
*
|
||||
* 以固定 8KB 缓冲区流式读取输入,内存占用恒定,适用于任意大小的文件与数据流。
|
||||
* 每次调用 [hash] 都会新建 [MessageDigest] 实例(其本身非线程安全),
|
||||
* 因此本类实例无状态、可安全地在多线程间共享。
|
||||
*
|
||||
* 遵循 [HashCodec] 契约:不关闭输入流,由调用方负责流的生命周期。
|
||||
*
|
||||
* 子类只需指定算法名称,也可借此扩展 JDK 默认提供者之外的算法
|
||||
* (如 BouncyCastle 提供的 SM3),前提是相应 [java.security.Provider] 已注册。
|
||||
*
|
||||
* @param algorithm [MessageDigest.getInstance] 所用的算法名称
|
||||
*/
|
||||
abstract class MessageDigestCodec(private val algorithm: String) : HashCodec {
|
||||
|
||||
/**
|
||||
* 以 8KB 缓冲区流式计算输入流内容的哈希值。
|
||||
*
|
||||
* 不关闭输入流;每次调用新建 [MessageDigest] 实例,线程安全。
|
||||
*
|
||||
* @param input 待计算哈希的输入流
|
||||
* @return 哈希结果字节数组
|
||||
* @throws java.security.NoSuchAlgorithmException 当前环境无指定算法的提供者时抛出
|
||||
*/
|
||||
override fun hash(input: InputStream): ByteArray {
|
||||
val digest = MessageDigest.getInstance(algorithm)
|
||||
val buffer = ByteArray(8192)
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n == -1) break
|
||||
digest.update(buffer, 0, n)
|
||||
}
|
||||
return digest.digest()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* 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 Sha1Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* SHA-1 哈希编解码器(输出 160 位 / 20 字节)。
|
||||
*
|
||||
* SHA-1 已被证实存在碰撞攻击(SHAttered),不得用于安全场景,
|
||||
* 仅建议用于兼容遗留系统或非安全性校验。
|
||||
*/
|
||||
class Sha1Codec : MessageDigestCodec("SHA-1")
|
||||
+7
-7
@@ -15,14 +15,14 @@
|
||||
*
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile ApplicationStartedRunner.kt
|
||||
* LastUpdate 2026-03-11 08:46:40
|
||||
* CurrentFile Sha224Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.springboot.annotation
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
@Target(AnnotationTarget.FUNCTION)
|
||||
annotation class ApplicationStartedRunner(
|
||||
val order: Int = Int.MIN_VALUE,
|
||||
)
|
||||
/**
|
||||
* SHA-224 哈希编解码器(SHA-2 家族,输出 224 位 / 28 字节)。
|
||||
*/
|
||||
class Sha224Codec : MessageDigestCodec("SHA-224")
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* 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 Sha256Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* SHA-256 哈希编解码器(SHA-2 家族,输出 256 位 / 32 字节)。
|
||||
*
|
||||
* 目前广泛使用的安全哈希算法,适用于文件校验、数字签名、消息摘要等场景。
|
||||
*
|
||||
* 使用示例:
|
||||
* ```
|
||||
* val sha256 = Sha256Codec()
|
||||
* val hex = sha256.hashHex("hello")
|
||||
* val ok = sha256.verifyHash("hello", hex)
|
||||
* ```
|
||||
*/
|
||||
class Sha256Codec : MessageDigestCodec("SHA-256")
|
||||
+7
-11
@@ -15,18 +15,14 @@
|
||||
*
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile Listener.kt
|
||||
* LastUpdate 2026-03-10 09:04:02
|
||||
* CurrentFile Sha3224Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.springboot.annotation
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
import org.springframework.core.annotation.AliasFor
|
||||
import org.springframework.stereotype.Component
|
||||
|
||||
@Component
|
||||
annotation class Listener(
|
||||
@get:AliasFor(annotation = Component::class)
|
||||
val value: String = ""
|
||||
)
|
||||
/**
|
||||
* SHA3-224 哈希编解码器(SHA-3 家族,Keccak 结构,输出 224 位 / 28 字节)。
|
||||
*/
|
||||
class Sha3224Codec : MessageDigestCodec("SHA3-224")
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* 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 Sha3256Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* SHA3-256 哈希编解码器(SHA-3 家族,Keccak 结构,输出 256 位 / 32 字节)。
|
||||
*/
|
||||
class Sha3256Codec : MessageDigestCodec("SHA3-256")
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* 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 Sha3384Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* SHA3-384 哈希编解码器(SHA-3 家族,Keccak 结构,输出 384 位 / 48 字节)。
|
||||
*/
|
||||
class Sha3384Codec : MessageDigestCodec("SHA3-384")
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* 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 Sha3512Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:52
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* SHA3-512 哈希编解码器(SHA-3 家族,Keccak 结构,输出 512 位 / 64 字节)。
|
||||
*/
|
||||
class Sha3512Codec : MessageDigestCodec("SHA3-512")
|
||||
+7
-7
@@ -15,14 +15,14 @@
|
||||
*
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile ApplicationDestroyedRunner.kt
|
||||
* LastUpdate 2026-03-10 09:04:02
|
||||
* CurrentFile Sha384Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.springboot.annotation
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
@Target(AnnotationTarget.FUNCTION)
|
||||
annotation class ApplicationDestroyedRunner(
|
||||
val order: Int = Int.MIN_VALUE
|
||||
)
|
||||
/**
|
||||
* SHA-384 哈希编解码器(SHA-2 家族,输出 384 位 / 48 字节)。
|
||||
*/
|
||||
class Sha384Codec : MessageDigestCodec("SHA-384")
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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 Sha512224Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* SHA-512/224 哈希编解码器(SHA-2 家族,输出 224 位 / 28 字节)。
|
||||
*
|
||||
* 以 SHA-512 的运算结构截断输出至 224 位,在 64 位平台上性能优于 SHA-224。
|
||||
*/
|
||||
class Sha512224Codec : MessageDigestCodec("SHA-512/224")
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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 Sha512256Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* SHA-512/256 哈希编解码器(SHA-2 家族,输出 256 位 / 32 字节)。
|
||||
*
|
||||
* 以 SHA-512 的运算结构截断输出至 256 位,在 64 位平台上性能优于 SHA-256。
|
||||
*/
|
||||
class Sha512256Codec : MessageDigestCodec("SHA-512/256")
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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 Sha512Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* SHA-512 哈希编解码器(SHA-2 家族,输出 512 位 / 64 字节)。
|
||||
*
|
||||
* 在 64 位平台上通常比 SHA-256 更快,适用于大文件校验与高安全需求场景。
|
||||
*/
|
||||
class Sha512Codec : MessageDigestCodec("SHA-512")
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* 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 FastBaseMapper.kt
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile BaseResponse.kt
|
||||
* LastUpdate 2026-10-26 23:22:18
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.http
|
||||
|
||||
/**
|
||||
* HTTP 响应基类,封装时间、消息、数据和状态码等通用响应字段。
|
||||
*
|
||||
* 除 [time] 外字段均可变,本身非线程安全;
|
||||
* 如需不可变更新语义,请使用子类的 with* 系列方法。
|
||||
*
|
||||
* @param T 响应数据的类型
|
||||
*/
|
||||
open class BaseResponse<T>(
|
||||
/** 响应时间(格式化的字符串),创建后不可修改 */
|
||||
open val time: String,
|
||||
/** 响应消息,可通过 setter 修改 */
|
||||
open var message: String,
|
||||
/** 响应数据,可通过 setter 修改 */
|
||||
open var data: T,
|
||||
/** HTTP 状态码,可通过 setter 修改 */
|
||||
open var statusCode: Int,
|
||||
|
||||
) {
|
||||
/**
|
||||
* 返回响应对象的字符串表示
|
||||
*
|
||||
* 重写toString方法以提供更有意义的对象表示,便于日志记录和调试。
|
||||
* 显示时间、消息、数据类型和值以及状态码。
|
||||
*
|
||||
* @return 格式化的字符串表示
|
||||
*/
|
||||
override fun toString(): String =
|
||||
"${javaClass.simpleName}(time=${time}, message=${message}, data=${data}, statusCode=${statusCode})"
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -26,4 +26,9 @@ package com.mingliqiye.utils.http
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
|
||||
|
||||
/**
|
||||
* 将本枚举转换为 OkHttp 的 [okhttp3.MediaType]。
|
||||
*
|
||||
* @return 与 [MediaType.value] 对应的 OkHttp 媒体类型
|
||||
*/
|
||||
fun MediaType.okhttp(): okhttp3.MediaType = this.value.toMediaType()
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* 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 FastBaseMapper.kt
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile PageData.kt
|
||||
* LastUpdate 2026-10-26 23:22:18
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.http
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
|
||||
/**
|
||||
* 分页数据类
|
||||
*/
|
||||
data class PageData<T>(
|
||||
/**
|
||||
* 当前页的数据列表
|
||||
*/
|
||||
val records: Collection<T> = emptyList(),
|
||||
|
||||
/**
|
||||
* 总条数(总记录数)
|
||||
*/
|
||||
val totalCount: Long = 0,
|
||||
|
||||
/**
|
||||
* 总页数
|
||||
*/
|
||||
val totalPages: Long = 0,
|
||||
|
||||
/**
|
||||
* 每页大小
|
||||
*/
|
||||
val pageSize: Long = 0,
|
||||
|
||||
/**
|
||||
* 当前页码(从 1 开始)
|
||||
*/
|
||||
val pageIndex: Long = 0,
|
||||
) {
|
||||
/** 伴生对象,提供工厂方法 */
|
||||
companion object {
|
||||
/**
|
||||
* 从 MyBatis-Plus 的分页对象构建分页数据
|
||||
*
|
||||
* @param T 记录类型
|
||||
* @param page MyBatis-Plus 分页对象
|
||||
* @return 转换后的分页数据
|
||||
*/
|
||||
fun <T> of(page: Page<T>): PageData<T> = PageData(
|
||||
records = page.records,
|
||||
totalCount = page.total,
|
||||
totalPages = page.pages,
|
||||
pageSize = page.size,
|
||||
pageIndex = page.current,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
/*
|
||||
* 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 FastBaseMapper.kt
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile PagedResponse.kt
|
||||
* LastUpdate 2026-10-26 23:22:18
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.http
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
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>(
|
||||
override val time: String, // 响应时间,一旦创建不可修改
|
||||
override var message: String, // 响应消息,可通过setter修改
|
||||
override var data: PageData<T>, // 响应数据,可通过setter修改
|
||||
override var statusCode: Int, // HTTP状态码,可通过setter修改
|
||||
) : BaseResponse<PageData<T>>(
|
||||
time,
|
||||
message,
|
||||
data,
|
||||
statusCode
|
||||
) {
|
||||
/** 伴生对象,提供各类分页响应的工厂方法 */
|
||||
companion object {
|
||||
/**
|
||||
* 创建一个默认的成功响应对象
|
||||
* 使用默认消息"操作成功",无数据,状态码200
|
||||
*
|
||||
* @return Response<Nothing> 默认的成功响应对象
|
||||
*/
|
||||
fun ok() = ok("操作成功")
|
||||
|
||||
|
||||
/**
|
||||
* 创建一个默认的错误响应对象
|
||||
* 使用默认消息"服务器错误",无数据,状态码500
|
||||
*
|
||||
* @return Response<Nothing> 默认的成功响应对象
|
||||
*/
|
||||
fun error() = error("服务器错误")
|
||||
|
||||
/**
|
||||
* 创建一个成功的响应对象(仅包含消息)
|
||||
*
|
||||
* @param message 响应消息
|
||||
* @return Response<Any> 成功的响应对象,数据为null
|
||||
*/
|
||||
@JvmStatic
|
||||
fun ok(message: String) = PagedResponse(
|
||||
time = DateTime.now().format(), message = message, data = PageData<Nothing>(), statusCode = 200
|
||||
)
|
||||
|
||||
/**
|
||||
* 创建一个错误的响应对象
|
||||
*
|
||||
* @param message 错误消息,默认为"服务器错误"
|
||||
* @param statusCode HTTP状态码,默认为500
|
||||
* @return Response<Any> 错误的响应对象
|
||||
*/
|
||||
fun error(message: String = "服务器错误", statusCode: Int = 500) = ok(message).withStatusCode(statusCode)
|
||||
|
||||
/**
|
||||
* 创建一个成功的响应对象(仅包含数据)
|
||||
* 使用默认消息"操作成功"
|
||||
*
|
||||
* @param T 响应数据的类型
|
||||
* @param data 响应数据
|
||||
* @return Response<T> 成功的响应对象,包含数据
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> okData(data: PageData<T>) = PagedResponse(
|
||||
time = DateTime.now().format(), message = "操作成功", data = data, statusCode = 200
|
||||
)
|
||||
|
||||
/**
|
||||
* 从mybatisplus的page构建
|
||||
*/
|
||||
@JvmOverloads
|
||||
fun <T> okPgae(
|
||||
page: Page<T>,
|
||||
time: String = DateTime.now().format(),
|
||||
message: String = "操作成功",
|
||||
statusCode: Int = 200,
|
||||
): PagedResponse<T> {
|
||||
|
||||
return PagedResponse(
|
||||
time = time, message = message, data = PageData.of(page), statusCode = statusCode
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个成功的响应对象(包含数据和消息)
|
||||
*
|
||||
* @param T 响应数据的类型
|
||||
* @param data 响应数据
|
||||
* @param message 响应消息
|
||||
* @return Response<T> 成功的响应对象,包含数据和消息
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> okData(data: PageData<T>, message: String) = PagedResponse(
|
||||
time = DateTime.now().format(), message = message, data = data, statusCode = 200
|
||||
)
|
||||
|
||||
/**
|
||||
* 创建一个指定状态码的响应对象(仅包含状态码)
|
||||
* 使用默认消息"操作成功",无数据
|
||||
*
|
||||
* @param statusCode HTTP状态码
|
||||
* @return Response<Any> 指定状态码的响应对象
|
||||
*/
|
||||
@JvmStatic
|
||||
fun code(statusCode: Int) = PagedResponse(
|
||||
time = DateTime.now().format(), message = "操作成功", data = PageData<Nothing>(), statusCode = statusCode
|
||||
)
|
||||
|
||||
/**
|
||||
* 创建一个指定状态码的响应对象(包含状态码和消息)
|
||||
* 无数据
|
||||
*
|
||||
* @param statusCode HTTP状态码
|
||||
* @param message 响应消息
|
||||
* @return Response<Any> 指定状态码和消息的响应对象
|
||||
*/
|
||||
@JvmStatic
|
||||
fun code(statusCode: Int, message: String) = PagedResponse(
|
||||
time = DateTime.now().format(), message = message, data = PageData<Nothing>(), statusCode = statusCode
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认构造函数,创建一个默认的成功响应对象
|
||||
* 使用当前时间、默认消息"操作成功"、状态码200、无数据
|
||||
*/
|
||||
constructor() : this(
|
||||
time = DateTime.now().format(), message = "操作成功", statusCode = 200, data = PageData()
|
||||
)
|
||||
|
||||
|
||||
/**
|
||||
* 设置响应数据
|
||||
*
|
||||
* 该方法允许修改响应数据,并返回当前对象以支持链式调用。
|
||||
*
|
||||
* @param data 新的响应数据
|
||||
* @return Response<T> 当前响应对象(支持链式调用)
|
||||
*/
|
||||
fun setData(data: PageData<T>): PagedResponse<T> {
|
||||
this.data = data
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个新的Response对象,使用指定的时间
|
||||
*
|
||||
* 该方法用于创建具有新时间的响应对象,遵循不可变对象的设计模式。
|
||||
* 如果时间相同,则返回原对象避免不必要的对象创建。
|
||||
*
|
||||
* @param time 新的响应时间
|
||||
* @return Response<T> 新的响应对象(如果时间相同则返回原对象)
|
||||
*/
|
||||
fun withTime(time: String): PagedResponse<T> =
|
||||
if (this.time == time) this else PagedResponse(time, message, data, statusCode)
|
||||
|
||||
/**
|
||||
* 创建一个新的Response对象,使用指定的数据
|
||||
*
|
||||
* 该方法允许改变响应数据的类型,创建一个新的响应对象。
|
||||
* 适用于需要在保持其他字段不变的情况下更新数据类型的场景。
|
||||
*
|
||||
* @param D 新的数据类型
|
||||
* @param data 新的响应数据
|
||||
* @return Response<D> 新的响应对象,数据类型为D
|
||||
*/
|
||||
fun <D> withData(data: PageData<D>): PagedResponse<D> =
|
||||
PagedResponse(this.time, this.message, data, this.statusCode)
|
||||
|
||||
/**
|
||||
* 创建一个新的Response对象,使用指定的消息
|
||||
*
|
||||
* 该方法用于创建具有新消息的响应对象,遵循不可变对象的设计模式。
|
||||
* 如果消息相同,则返回原对象避免不必要的对象创建。
|
||||
*
|
||||
* @param message 新的响应消息
|
||||
* @return Response<T> 新的响应对象(如果消息相同则返回原对象)
|
||||
*/
|
||||
fun withMessage(message: String): PagedResponse<T> =
|
||||
if (this.message == message) this else PagedResponse(time, message, data, statusCode)
|
||||
|
||||
/**
|
||||
* 创建一个新的Response对象,使用指定的状态码
|
||||
*
|
||||
* 该方法用于创建具有新状态码的响应对象,遵循不可变对象的设计模式。
|
||||
* 如果状态码相同,则返回原对象避免不必要的对象创建。
|
||||
*
|
||||
* @param statusCode 新的状态码
|
||||
* @return Response<T> 新的响应对象(如果状态码相同则返回原对象)
|
||||
*/
|
||||
fun withStatusCode(statusCode: Int): PagedResponse<T> =
|
||||
if (this.statusCode == statusCode) this else PagedResponse(time, message, data, statusCode)
|
||||
|
||||
}
|
||||
@@ -13,10 +13,10 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
* ProjectName mingli-utils
|
||||
* ProjectName FastBaseMapper.kt
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile Response.kt
|
||||
* LastUpdate 2026-03-14 08:01:32
|
||||
* LastUpdate 2026-10-26 23:22:18
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -38,12 +38,18 @@ import com.mingliqiye.utils.time.DateTime
|
||||
* @property statusCode HTTP状态码
|
||||
*/
|
||||
data class Response<T>(
|
||||
private val time: String, // 响应时间,一旦创建不可修改
|
||||
private var message: String, // 响应消息,可通过setter修改
|
||||
private var data: T?, // 响应数据,可通过setter修改
|
||||
private var statusCode: Int, // HTTP状态码,可通过setter修改
|
||||
override val time: String, // 响应时间,一旦创建不可修改
|
||||
override var message: String, // 响应消息,可通过setter修改
|
||||
override var data: T?, // 响应数据,可通过setter修改
|
||||
override var statusCode: Int, // HTTP状态码,可通过setter修改
|
||||
) : BaseResponse<T?>(
|
||||
time,
|
||||
message,
|
||||
data,
|
||||
statusCode,
|
||||
) {
|
||||
|
||||
/** 伴生对象,提供各类响应的工厂方法 */
|
||||
companion object {
|
||||
/**
|
||||
* 创建一个默认的成功响应对象
|
||||
@@ -70,10 +76,7 @@ data class Response<T>(
|
||||
*/
|
||||
@JvmStatic
|
||||
fun ok(message: String) = Response(
|
||||
time = DateTime.now().format(),
|
||||
message = message,
|
||||
data = null,
|
||||
statusCode = 200
|
||||
time = DateTime.now().format(), message = message, data = null, statusCode = 200
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -95,10 +98,7 @@ data class Response<T>(
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> okData(data: T) = Response(
|
||||
time = DateTime.now().format(),
|
||||
message = "操作成功",
|
||||
data = data,
|
||||
statusCode = 200
|
||||
time = DateTime.now().format(), message = "操作成功", data = data, statusCode = 200
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -111,10 +111,7 @@ data class Response<T>(
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> okData(data: T, message: String) = Response(
|
||||
time = DateTime.now().format(),
|
||||
message = message,
|
||||
data = data,
|
||||
statusCode = 200
|
||||
time = DateTime.now().format(), message = message, data = data, statusCode = 200
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -126,10 +123,7 @@ data class Response<T>(
|
||||
*/
|
||||
@JvmStatic
|
||||
fun code(statusCode: Int) = Response(
|
||||
time = DateTime.now().format(),
|
||||
message = "操作成功",
|
||||
data = null,
|
||||
statusCode = statusCode
|
||||
time = DateTime.now().format(), message = "操作成功", data = null, statusCode = statusCode
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -142,10 +136,7 @@ data class Response<T>(
|
||||
*/
|
||||
@JvmStatic
|
||||
fun code(statusCode: Int, message: String) = Response(
|
||||
time = DateTime.now().format(),
|
||||
message = message,
|
||||
data = null,
|
||||
statusCode = statusCode
|
||||
time = DateTime.now().format(), message = message, data = null, statusCode = statusCode
|
||||
)
|
||||
}
|
||||
|
||||
@@ -154,75 +145,9 @@ data class Response<T>(
|
||||
* 使用当前时间、默认消息"操作成功"、状态码200、无数据
|
||||
*/
|
||||
constructor() : this(
|
||||
time = DateTime.now().format(),
|
||||
message = "操作成功",
|
||||
statusCode = 200,
|
||||
data = null
|
||||
time = DateTime.now().format(), message = "操作成功", statusCode = 200, data = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 获取格式化后的时间字符串。
|
||||
*
|
||||
* @return 格式化后的时间字符串
|
||||
*/
|
||||
fun getTime(): String = time
|
||||
|
||||
/**
|
||||
* 获取响应消息
|
||||
*
|
||||
* @return String 当前响应消息
|
||||
*/
|
||||
fun getMessage(): String = message
|
||||
|
||||
/**
|
||||
* 设置响应消息
|
||||
*
|
||||
* 该方法允许修改响应消息,并返回当前对象以支持链式调用。
|
||||
*
|
||||
* @param message 新的响应消息
|
||||
* @return Response<T> 当前响应对象(支持链式调用)
|
||||
*/
|
||||
fun setMessage(message: String): Response<T> {
|
||||
this.message = message
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取响应数据
|
||||
*
|
||||
* 返回的响应数据可能为null,调用前应进行空值检查。
|
||||
*
|
||||
* @return T? 响应数据,可能为空
|
||||
*/
|
||||
fun getData(): T? = data
|
||||
|
||||
/**
|
||||
* 获取非空数据对象
|
||||
*
|
||||
* 该方法强制解包data属性,如果data为null则会抛出NullPointerException异常。
|
||||
* 适用于确定data不为null的场景,避免重复的空值检查。
|
||||
*
|
||||
* @return T 非空的数据对象
|
||||
* @throws NullPointerException 当data属性为null时抛出此异常
|
||||
*/
|
||||
@Throws(NullPointerException::class)
|
||||
fun notNullData(): T {
|
||||
return data ?: throw NullPointerException("at Response.notNullData() because data is null")
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置响应数据
|
||||
*
|
||||
* 该方法允许修改响应数据,并返回当前对象以支持链式调用。
|
||||
*
|
||||
* @param data 新的响应数据
|
||||
* @return Response<T> 当前响应对象(支持链式调用)
|
||||
*/
|
||||
fun setData(data: T): Response<T> {
|
||||
this.data = data
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个新的Response对象,使用指定的时间
|
||||
*
|
||||
@@ -232,8 +157,7 @@ data class Response<T>(
|
||||
* @param time 新的响应时间
|
||||
* @return Response<T> 新的响应对象(如果时间相同则返回原对象)
|
||||
*/
|
||||
fun withTime(time: String): Response<T> =
|
||||
if (this.time == time) this else Response(time, message, data, statusCode)
|
||||
fun withTime(time: String): Response<T> = if (this.time == time) this else Response(time, message, data, statusCode)
|
||||
|
||||
/**
|
||||
* 创建一个新的Response对象,使用指定的数据
|
||||
@@ -245,8 +169,7 @@ data class Response<T>(
|
||||
* @param data 新的响应数据
|
||||
* @return Response<D> 新的响应对象,数据类型为D
|
||||
*/
|
||||
fun <D> withData(data: D): Response<D> =
|
||||
Response(this.time, this.message, data, this.statusCode)
|
||||
fun <D> withData(data: D): Response<D> = Response(this.time, this.message, data, this.statusCode)
|
||||
|
||||
/**
|
||||
* 创建一个新的Response对象,使用指定的消息
|
||||
@@ -272,25 +195,6 @@ data class Response<T>(
|
||||
fun withStatusCode(statusCode: Int): Response<T> =
|
||||
if (this.statusCode == statusCode) this else Response(time, message, data, statusCode)
|
||||
|
||||
/**
|
||||
* 获取状态码
|
||||
*
|
||||
* @return Int 当前HTTP状态码
|
||||
*/
|
||||
fun getStatusCode(): Int = statusCode
|
||||
|
||||
/**
|
||||
* 设置状态码
|
||||
*
|
||||
* 该方法允许修改状态码,并返回当前对象以支持链式调用。
|
||||
*
|
||||
* @param statusCode 新的HTTP状态码
|
||||
* @return Response<T> 当前响应对象(支持链式调用)
|
||||
*/
|
||||
fun setStatusCode(statusCode: Int): Response<T> {
|
||||
this.statusCode = statusCode
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回响应对象的字符串表示
|
||||
@@ -301,5 +205,5 @@ data class Response<T>(
|
||||
* @return 格式化的字符串表示
|
||||
*/
|
||||
override fun toString(): String =
|
||||
"Response<${data?.javaClass?.simpleName ?: "Nothing"}>(time=${getTime()}, message=${getMessage()}, data=${getData()}, statusCode=${getStatusCode()})"
|
||||
"Response<${data?.javaClass?.simpleName ?: "Nothing"}>(time=${time}, message=${message}, data=${data}, statusCode=${statusCode})"
|
||||
}
|
||||
|
||||
@@ -16,45 +16,307 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile OkHttpUtils.kt
|
||||
* LastUpdate 2026-10-22 20:20:42
|
||||
* LastUpdate 2026-11-09 19:18:03
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
@file:JvmName("OkHttpUtils")
|
||||
|
||||
package com.mingliqiye.utils.http.okhttp
|
||||
|
||||
import com.mingliqiye.utils.http.MediaType
|
||||
import com.mingliqiye.utils.http.okhttp
|
||||
import com.mingliqiye.utils.json.api.JSONA
|
||||
import com.mingliqiye.utils.json.api.base.JsonApi
|
||||
import com.mingliqiye.utils.json.api.base.JsonApi.Companion.parse
|
||||
import okhttp3.Call
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
|
||||
import okhttp3.*
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
|
||||
/**
|
||||
* 将 OkHttp 的 [Response] 响应体解析为指定泛型类型的对象。
|
||||
*
|
||||
* 会读取并关闭响应体。未显式传入 [jsonApi] 时使用 [JSONA.jsonApi]。
|
||||
*
|
||||
* @param T 目标对象类型,由调用方通过 reified 推断
|
||||
* @param jsonApi 可选的 [JsonApi] 实例;为 `null` 时使用 [JSONA.jsonApi]
|
||||
* @return 解析后的对象实例
|
||||
* @throws NullPointerException 未传入 [jsonApi] 且 [JSONA] 尚未注入实例时抛出
|
||||
*/
|
||||
inline fun <reified T> Response.json(jsonApi: JsonApi? = null): T = body.use {
|
||||
if (jsonApi != null) {
|
||||
return jsonApi.parse<T>(it.bytes())
|
||||
} else {
|
||||
JSONA.parse<T>(it.bytes())
|
||||
}
|
||||
(jsonApi ?: JSONA.jsonApi).parse<T>(it.bytes())
|
||||
}
|
||||
|
||||
fun Response.text() = body.use {
|
||||
String(it.bytes())
|
||||
}
|
||||
/**
|
||||
* 读取 [Response] 响应体为字符串,并关闭响应体。
|
||||
*
|
||||
* 按响应 `Content-Type` 的 `charset` 解码,缺省 UTF-8;读取后响应体被关闭。
|
||||
*
|
||||
* @return 响应体内容字符串
|
||||
*/
|
||||
fun Response.text() = this.body.string()
|
||||
|
||||
/**
|
||||
* 创建一个 [Request],通过 [calld] 配置 [Request.Builder]。
|
||||
*
|
||||
* @param calld 在 [Request.Builder] 上执行的配置块
|
||||
* @return 构建完成的 [Request]
|
||||
*/
|
||||
fun newRequest(calld: Request.Builder.() -> Unit): Request =
|
||||
Request.Builder().apply(calld).build()
|
||||
|
||||
fun newRequest(calld: Request.Builder.() -> Unit): Request {
|
||||
val request = Request.Builder()
|
||||
calld(request)
|
||||
return request.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用当前 [OkHttpClient] 创建一个 [Call],请求通过 [calld] 配置。
|
||||
*
|
||||
* 调用返回的 [Call] 的 `execute()` 或 `enqueue()` 才会真正发起请求。
|
||||
*
|
||||
* @param calld 在 [Request.Builder] 上执行的配置块
|
||||
* @return 未执行的 [Call]
|
||||
*/
|
||||
fun OkHttpClient.newCall(calld: Request.Builder.() -> Unit): Call {
|
||||
return this.newCall(newRequest(calld))
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用当前 [OkHttpClient] 同步执行一次请求,请求通过 [calld] 配置。
|
||||
*
|
||||
* 注意:在 Android 主线程调用会抛出 `NetworkOnMainThreadException`。
|
||||
*
|
||||
* @param calld 在 [Request.Builder] 上执行的配置块
|
||||
* @return 同步执行得到的 [Response]
|
||||
* @throws java.io.IOException 网络或 I/O 失败时抛出
|
||||
*/
|
||||
fun OkHttpClient.newExecute(calld: Request.Builder.() -> Unit): Response {
|
||||
return this.newCall(newRequest(calld)).execute()
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置 URL,并通过 [calld] 配置查询参数。
|
||||
*
|
||||
* 示例:
|
||||
* ```
|
||||
* Request.Builder().url("https://example.com/api") {
|
||||
* addQueryParameter("page", "1")
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param url 基础 URL 字符串
|
||||
* @param calld 可选的 [HttpUrl.Builder] 配置块(如添加查询参数);为 `null` 时直接使用 [url]
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.url(
|
||||
url: String,
|
||||
calld: (HttpUrl.Builder.() -> Unit)? = null,
|
||||
): Request.Builder {
|
||||
return if (calld != null) {
|
||||
this.url(url.toHttpUrl().newBuilder().apply { calld() }.build())
|
||||
} else {
|
||||
this.url(url.toHttpUrl())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置请求方法和字节数组请求体。
|
||||
*
|
||||
* @param method 请求方法
|
||||
* @param body 请求体字节数组
|
||||
* @param mediaType 可选的媒体类型;为 `null` 时不设置 Content-Type
|
||||
* @param offset 起始偏移量,默认 0
|
||||
* @param length 读取长度,默认从 [offset] 到 [body] 末尾
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.methodBody(
|
||||
method: Method,
|
||||
body: ByteArray,
|
||||
mediaType: MediaType? = null,
|
||||
offset: Int = 0,
|
||||
length: Int = body.size - offset,
|
||||
): Request.Builder {
|
||||
require(offset >= 0 && length >= 0 && offset + length <= body.size) {
|
||||
"offset/length 越界: offset=$offset, length=$length, size=${body.size}"
|
||||
}
|
||||
return method(method.name, body.toRequestBody(mediaType?.okhttp(), offset, length))
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置请求方法,并将对象序列化为 JSON 作为请求体。
|
||||
*
|
||||
* @param method 请求方法
|
||||
* @param body 待序列化的对象
|
||||
* @param jsonApi 可选的 [JsonApi] 实例;为 `null` 时使用 [JSONA.jsonApi]
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.methodJsonBody(
|
||||
method: Method,
|
||||
body: Any,
|
||||
jsonApi: JsonApi? = null,
|
||||
): Request.Builder = methodBody(
|
||||
method,
|
||||
(jsonApi ?: JSONA.jsonApi).formatBytes(body),
|
||||
MediaType.APPLICATION_JSON,
|
||||
)
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置 GET 方法,并将对象序列化为 JSON 作为请求体。
|
||||
*
|
||||
* 注意:GET 请求携带请求体在 HTTP 语义中不常见,部分服务端可能忽略或拒绝。
|
||||
*
|
||||
* @param body 待序列化的对象
|
||||
* @param jsonApi 可选的 [JsonApi] 实例;为 `null` 时使用 [JSONA.jsonApi]
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.getJsonBody(
|
||||
body: Any,
|
||||
jsonApi: JsonApi? = null,
|
||||
) = methodBody(
|
||||
Method.GET,
|
||||
(jsonApi ?: JSONA.jsonApi).formatBytes(body),
|
||||
MediaType.APPLICATION_JSON,
|
||||
)
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置 POST 方法,并将对象序列化为 JSON 作为请求体。
|
||||
*
|
||||
* @param body 待序列化的对象
|
||||
* @param jsonApi 可选的 [JsonApi] 实例;为 `null` 时使用 [JSONA.jsonApi]
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.postJsonBody(
|
||||
body: Any,
|
||||
jsonApi: JsonApi? = null,
|
||||
) = methodBody(
|
||||
Method.POST,
|
||||
(jsonApi ?: JSONA.jsonApi).formatBytes(body),
|
||||
MediaType.APPLICATION_JSON,
|
||||
)
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置 PUT 方法,并将对象序列化为 JSON 作为请求体。
|
||||
*
|
||||
* @param body 待序列化的对象
|
||||
* @param jsonApi 可选的 [JsonApi] 实例;为 `null` 时使用 [JSONA.jsonApi]
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.putJsonBody(
|
||||
body: Any,
|
||||
jsonApi: JsonApi? = null,
|
||||
) = methodBody(
|
||||
Method.PUT,
|
||||
(jsonApi ?: JSONA.jsonApi).formatBytes(body),
|
||||
MediaType.APPLICATION_JSON,
|
||||
)
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置 DELETE 方法,并将对象序列化为 JSON 作为请求体。
|
||||
*
|
||||
* @param body 待序列化的对象
|
||||
* @param jsonApi 可选的 [JsonApi] 实例;为 `null` 时使用 [JSONA.jsonApi]
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.deleteJsonBody(
|
||||
body: Any,
|
||||
jsonApi: JsonApi? = null,
|
||||
) = methodBody(
|
||||
Method.DELETE,
|
||||
(jsonApi ?: JSONA.jsonApi).formatBytes(body),
|
||||
MediaType.APPLICATION_JSON,
|
||||
)
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置 HEAD 方法,并将对象序列化为 JSON 作为请求体。
|
||||
*
|
||||
* 注意:HEAD 请求通常不应携带请求体,部分服务端可能忽略或拒绝。
|
||||
*
|
||||
* @param body 待序列化的对象
|
||||
* @param jsonApi 可选的 [JsonApi] 实例;为 `null` 时使用 [JSONA.jsonApi]
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.headJsonBody(
|
||||
body: Any,
|
||||
jsonApi: JsonApi? = null,
|
||||
) = methodBody(
|
||||
Method.HEAD,
|
||||
(jsonApi ?: JSONA.jsonApi).formatBytes(body),
|
||||
MediaType.APPLICATION_JSON,
|
||||
)
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置 OPTIONS 方法,并将对象序列化为 JSON 作为请求体。
|
||||
*
|
||||
* @param body 待序列化的对象
|
||||
* @param jsonApi 可选的 [JsonApi] 实例;为 `null` 时使用 [JSONA.jsonApi]
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.optionsJsonBody(
|
||||
body: Any,
|
||||
jsonApi: JsonApi? = null,
|
||||
) = methodBody(
|
||||
Method.OPTIONS,
|
||||
(jsonApi ?: JSONA.jsonApi).formatBytes(body),
|
||||
MediaType.APPLICATION_JSON,
|
||||
)
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置 QUERY 方法,并将对象序列化为 JSON 作为请求体。
|
||||
*
|
||||
* QUERY 是 HTTP 扩展方法,需服务端支持。
|
||||
*
|
||||
* @param body 待序列化的对象
|
||||
* @param jsonApi 可选的 [JsonApi] 实例;为 `null` 时使用 [JSONA.jsonApi]
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.queryJsonBody(
|
||||
body: Any,
|
||||
jsonApi: JsonApi? = null,
|
||||
) = methodBody(
|
||||
Method.QUERY,
|
||||
(jsonApi ?: JSONA.jsonApi).formatBytes(body),
|
||||
MediaType.APPLICATION_JSON,
|
||||
)
|
||||
|
||||
/**
|
||||
* HTTP 请求方法枚举,供 [Request.Builder.methodBody] 等扩展使用。
|
||||
*/
|
||||
enum class Method {
|
||||
/** GET 方法。 */
|
||||
GET,
|
||||
|
||||
/** POST 方法。 */
|
||||
POST,
|
||||
|
||||
/** PUT 方法。 */
|
||||
PUT,
|
||||
|
||||
/** DELETE 方法。 */
|
||||
DELETE,
|
||||
|
||||
/** HEAD 方法。 */
|
||||
HEAD,
|
||||
|
||||
/** OPTIONS 方法。 */
|
||||
OPTIONS,
|
||||
|
||||
/** QUERY 方法(HTTP 扩展方法,需服务端支持)。 */
|
||||
QUERY,
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置 POST 方法,使用空请求体。
|
||||
*
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.post() = post(RequestBody.EMPTY)
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置 PUT 方法,使用空请求体。
|
||||
*
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.put() = put(RequestBody.EMPTY)
|
||||
|
||||
/**
|
||||
* 在 [Request.Builder] 上设置 PATCH 方法,使用空请求体。
|
||||
*
|
||||
* @return 当前 [Request.Builder],便于链式调用
|
||||
*/
|
||||
fun Request.Builder.patch() = patch(RequestBody.EMPTY)
|
||||
|
||||
@@ -28,16 +28,37 @@ import java.io.OutputStream
|
||||
import java.nio.charset.Charset
|
||||
|
||||
|
||||
/**
|
||||
* 读取输入流中的全部字节并按指定字符集解码为字符串。
|
||||
*
|
||||
* @param charset 字符编码,默认为 [Charsets.UTF_8]
|
||||
* @return 解码后的字符串
|
||||
*/
|
||||
fun InputStream.readAllText(charset: Charset = Charsets.UTF_8) = this.readAllBytes().toString(charset)
|
||||
|
||||
/**
|
||||
* 将输入流中的全部字节导出到指定输出流,并刷新输出流。
|
||||
*
|
||||
* @param out 目标输出流
|
||||
*/
|
||||
fun InputStream.exportBytes(out: OutputStream) {
|
||||
out.write(this.readAllBytes())
|
||||
out.flush()
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取输入流中的全部字节并转换为字节列表。
|
||||
*
|
||||
* @return 包含全部字节的列表
|
||||
*/
|
||||
fun InputStream.readToList(): List<Byte> = this.readBytes().toList()
|
||||
|
||||
|
||||
/**
|
||||
* 读取输入流中的全部字节。
|
||||
*
|
||||
* @return 包含全部字节的字节数组
|
||||
*/
|
||||
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
|
||||
@JvmName("readInputStreamAllBytes")
|
||||
fun InputStream.readAllBytes(): ByteArray = this.readBytes()
|
||||
|
||||
@@ -44,10 +44,24 @@ object SIO {
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展函数:条件不满足时对当前对象执行给定变换函数
|
||||
*
|
||||
* @param boolean 条件值,为 true 时直接返回原对象
|
||||
* @param pd 条件为 false 时执行的变换函数
|
||||
* @return 原对象或变换后的对象
|
||||
*/
|
||||
fun <T> T.ifOr(boolean: Boolean, pd: T.() -> T): T = if (boolean) {
|
||||
this
|
||||
} else pd(this)
|
||||
|
||||
/**
|
||||
* 扩展函数:条件满足时对当前对象执行给定变换函数
|
||||
*
|
||||
* @param boolean 条件值,为 false 时直接返回原对象
|
||||
* @param pd 条件为 true 时执行的变换函数
|
||||
* @return 原对象或变换后的对象
|
||||
*/
|
||||
fun <T> T.ifOrElse(boolean: Boolean, pd: T.() -> T): T = if (!boolean) {
|
||||
this
|
||||
} else pd(this)
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile FieldStructure.kt
|
||||
* LastUpdate 2026-07-02 10:22:42
|
||||
* LastUpdate 2026-11-04 11:53:07
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -30,7 +30,7 @@ import java.lang.reflect.Modifier
|
||||
* 该类继承自JNA的Structure类,通过反射自动获取子类的公共非静态字段,
|
||||
* 并按声明顺序返回字段名列表,用于JNA结构体的字段映射。
|
||||
*/
|
||||
open class FieldStructure : Structure() {
|
||||
abstract class FieldStructure : Structure() {
|
||||
/**
|
||||
* 获取结构体字段顺序列表
|
||||
* 通过反射遍历当前类及其父类的所有声明字段,过滤出公共非静态字段,
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile JSONA.kt
|
||||
* LastUpdate 2026-03-18 09:14:06
|
||||
* LastUpdate 2026-11-17 19:59:21
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -24,11 +24,11 @@ package com.mingliqiye.utils.json.api
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import com.fasterxml.jackson.module.kotlin.kotlinModule
|
||||
import com.mingliqiye.utils.json.api.JSONA.jsonApi
|
||||
import com.mingliqiye.utils.json.api.JSONA.setJsonApi
|
||||
import com.mingliqiye.utils.json.api.base.JsonApi
|
||||
import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
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 java.io.File
|
||||
import java.io.IOException
|
||||
@@ -38,523 +38,567 @@ import java.nio.file.Path
|
||||
import kotlin.io.path.readBytes
|
||||
|
||||
/**
|
||||
* JSON工具类,提供静态方法访问JSON API功能
|
||||
* JSON 工具门面,提供静态方法访问 JSON API 功能。
|
||||
*
|
||||
* [JSONA] 本身不实现 JSON 逻辑,而是持有一个可替换的 [JsonApi] 实例,
|
||||
* 所有方法都转发到当前实例。使用前必须先通过 [setJsonApi] 注入实现,
|
||||
* 未注入时访问 [jsonApi] 或调用任何转发方法都会抛出 [NullPointerException]。
|
||||
*
|
||||
* @see JsonApi
|
||||
* @see setJsonApi
|
||||
*/
|
||||
object JSONA {
|
||||
@JvmStatic
|
||||
private var jsonApi: JsonApi? = null
|
||||
|
||||
/**
|
||||
* 获取JSON API实例
|
||||
* 当前 JSON API 实例,未注入时为 `null`。
|
||||
*
|
||||
* @return JSON API实例
|
||||
* @throws NullPointerException 当JSON API未初始化时抛出异常
|
||||
* 使用 `@Volatile` 保证多线程下的可见性;仅在启动时注入一次的场景下无副作用。
|
||||
*/
|
||||
@Throws(NullPointerException::class)
|
||||
@Volatile
|
||||
@JvmStatic
|
||||
fun getJsonApi(): JsonApi {
|
||||
if (jsonApi == null) {
|
||||
throw NullPointerException("jsonApi is null plase setJsonApi first")
|
||||
}
|
||||
return jsonApi!!
|
||||
}
|
||||
private var privateJsonApi: JsonApi? = null
|
||||
|
||||
/**
|
||||
* 设置JSON API实例
|
||||
* 获取当前 JSON API 实例。
|
||||
*
|
||||
* @param jsa JSON API实例
|
||||
* @return 已注入的 [JsonApi] 实例
|
||||
* @throws NullPointerException 尚未调用 [setJsonApi] 时抛出
|
||||
*/
|
||||
@JvmStatic
|
||||
val jsonApi: JsonApi
|
||||
get() = privateJsonApi ?: throw NullPointerException("jsonApi is null plase setJsonApi first")
|
||||
|
||||
/**
|
||||
* 设置或替换 JSON API 实例。
|
||||
*
|
||||
* 设置后,[JSONA] 上所有转发方法立即使用新实例。
|
||||
*
|
||||
* @param jsa JSON API 实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun setJsonApi(jsa: JsonApi) {
|
||||
jsonApi = jsa
|
||||
privateJsonApi = jsa
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用反射创建并设置指定类型的JSON API实例
|
||||
* 通过反射创建 [T] 的无参实例并设置为当前 JSON API。
|
||||
*
|
||||
* @param T 继承自JsonApi的具体实现类
|
||||
* @param T 继承自 [JsonApi] 的具体实现类,必须提供公开无参构造
|
||||
* @throws NoSuchMethodException 实现类没有无参构造时抛出
|
||||
* @throws ReflectiveOperationException 反射实例化失败时抛出
|
||||
*/
|
||||
inline fun <reified T : JsonApi> setJsonApi() {
|
||||
setJsonApi(T::class.java.getConstructor().newInstance() as JsonApi)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为指定类型的对象
|
||||
* 将 JSON 字符串解析为指定类型的对象。
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param clazz 目标对象的Class类型
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型
|
||||
* @param json 待解析的 JSON 字符串
|
||||
* @param clazz 目标对象的 [Class] 类型
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parse(json: String, clazz: Class<T>): T = getJsonApi().parse(json, clazz)
|
||||
fun <T> parse(json: String, clazz: Class<T>): T = jsonApi.parse(json, clazz)
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为指定泛型类型对象
|
||||
* 将 JSON 字符串解析为指定泛型类型的对象。
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型,由调用方通过 reified 推断
|
||||
* @param json 待解析的 JSON 字符串
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
inline fun <reified T> parse(json: String): T {
|
||||
return getJsonApi().parse(json, (object : JsonTypeReference<T>() {}))
|
||||
return jsonApi.parse(json, (object : JsonTypeReference<T>() {}))
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字节数组形式的JSON解析为指定泛型类型对象
|
||||
* 将字节数组形式的 JSON 解析为指定泛型类型的对象。
|
||||
*
|
||||
* @param json 待解析的JSON字节数组
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型,由调用方通过 reified 推断
|
||||
* @param json 待解析的 JSON 字节数组
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
inline fun <reified T> parse(json: ByteArray): T = getJsonApi().parse(json, object : JsonTypeReference<T>() {})
|
||||
inline fun <reified T> parse(json: ByteArray): T = jsonApi.parse(json, object : JsonTypeReference<T>() {})
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为指定泛型类型对象
|
||||
* 将 JSON 字符串解析为指定泛型类型的对象。
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param type 目标对象的Type类型(支持泛型)
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型
|
||||
* @param json 待解析的 JSON 字符串
|
||||
* @param type 目标对象的 [JsonTypeReference] 类型引用(支持泛型)
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parse(json: String, type: JsonTypeReference<T>): T = getJsonApi().parse(json, type)
|
||||
fun <T> parse(json: String, type: JsonTypeReference<T>): T = jsonApi.parse(json, type)
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON字符串
|
||||
* 将对象格式化为 JSON 字符串。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @return 格式化后的JSON字符串
|
||||
* @return 格式化后的 JSON 字符串
|
||||
*/
|
||||
@JvmStatic
|
||||
fun format(obj: Any): String = getJsonApi().format(obj)
|
||||
|
||||
fun format(obj: Any): String = jsonApi.format(obj)
|
||||
|
||||
/**
|
||||
* 从文件路径解析JSON为指定类型的对象
|
||||
* 从文件路径解析 JSON 为指定类型的对象。
|
||||
*
|
||||
* @param T 目标对象类型
|
||||
* @param path 文件路径
|
||||
* @param clazz 目标对象的Class类型
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param clazz 目标对象的 [Class] 类型
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parseFrom(path: String, clazz: Class<T>): T = getJsonApi().parseFrom(path, clazz)
|
||||
fun <T> parseFrom(path: String, clazz: Class<T>): T = jsonApi.parseFrom(path, clazz)
|
||||
|
||||
/**
|
||||
* 从Path对象解析JSON为指定类型的对象
|
||||
* 从 [Path] 对象解析 JSON 为指定类型的对象。
|
||||
*
|
||||
* @param path Path对象
|
||||
* @param clazz 目标对象的Class类型
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型
|
||||
* @param path [Path] 对象
|
||||
* @param clazz 目标对象的 [Class] 类型
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parseFrom(path: Path, clazz: Class<T>): T = getJsonApi().parseFrom(path, clazz)
|
||||
fun <T> parseFrom(path: Path, clazz: Class<T>): T = jsonApi.parseFrom(path, clazz)
|
||||
|
||||
/**
|
||||
* 从File对象解析JSON为指定类型的对象
|
||||
* 从 [File] 对象解析 JSON 为指定类型的对象。
|
||||
*
|
||||
* @param file File对象
|
||||
* @param clazz 目标对象的Class类型
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型
|
||||
* @param file [File] 对象
|
||||
* @param clazz 目标对象的 [Class] 类型
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parseFrom(file: File, clazz: Class<T>): T = getJsonApi().parseFrom(file, clazz)
|
||||
fun <T> parseFrom(file: File, clazz: Class<T>): T = jsonApi.parseFrom(file, clazz)
|
||||
|
||||
/**
|
||||
* 从InputStream解析JSON为指定类型的对象
|
||||
* 从 [InputStream] 解析 JSON 为指定类型的对象。
|
||||
*
|
||||
* @param inputStream InputStream对象
|
||||
* @param clazz 目标对象的Class类型
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型
|
||||
* @param inputStream [InputStream] 对象
|
||||
* @param clazz 目标对象的 [Class] 类型
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parseFrom(inputStream: InputStream, clazz: Class<T>): T = getJsonApi().parseFrom(inputStream, clazz)
|
||||
fun <T> parseFrom(inputStream: InputStream, clazz: Class<T>): T = jsonApi.parseFrom(inputStream, clazz)
|
||||
|
||||
/**
|
||||
* 从文件路径解析JSON为指定泛型类型对象
|
||||
* 从文件路径解析 JSON 为指定泛型类型的对象。
|
||||
*
|
||||
* @param T 目标对象类型
|
||||
* @param path 文件路径
|
||||
* @param type 目标对象的Type类型(支持泛型)
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param type 目标对象的 [JsonTypeReference] 类型引用(支持泛型)
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parseFrom(path: String, type: JsonTypeReference<T>): T = getJsonApi().parseFrom(path, type)
|
||||
fun <T> parseFrom(path: String, type: JsonTypeReference<T>): T = jsonApi.parseFrom(path, type)
|
||||
|
||||
/**
|
||||
* 从Path对象解析JSON为指定泛型类型对象
|
||||
* 从 [Path] 对象解析 JSON 为指定泛型类型的对象。
|
||||
*
|
||||
* @param path Path对象
|
||||
* @param type 目标对象的Type类型(支持泛型)
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型
|
||||
* @param path [Path] 对象
|
||||
* @param type 目标对象的 [JsonTypeReference] 类型引用(支持泛型)
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parseFrom(path: Path, type: JsonTypeReference<T>): T = getJsonApi().parseFrom(path, type)
|
||||
fun <T> parseFrom(path: Path, type: JsonTypeReference<T>): T = jsonApi.parseFrom(path, type)
|
||||
|
||||
/**
|
||||
* 从File对象解析JSON为指定泛型类型对象
|
||||
* 从 [File] 对象解析 JSON 为指定泛型类型的对象。
|
||||
*
|
||||
* @param file File对象
|
||||
* @param type 目标对象的Type类型(支持泛型)
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型
|
||||
* @param file [File] 对象
|
||||
* @param type 目标对象的 [JsonTypeReference] 类型引用(支持泛型)
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parseFrom(file: File, type: JsonTypeReference<T>): T = getJsonApi().parseFrom(file, type)
|
||||
fun <T> parseFrom(file: File, type: JsonTypeReference<T>): T = jsonApi.parseFrom(file, type)
|
||||
|
||||
/**
|
||||
* 从InputStream解析JSON为指定泛型类型对象
|
||||
* 从 [InputStream] 解析 JSON 为指定泛型类型的对象。
|
||||
*
|
||||
* @param inputStream InputStream对象
|
||||
* @param type 目标对象的Type类型(支持泛型)
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型
|
||||
* @param inputStream [InputStream] 对象
|
||||
* @param type 目标对象的 [JsonTypeReference] 类型引用(支持泛型)
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parseFrom(inputStream: InputStream, type: JsonTypeReference<T>): T =
|
||||
getJsonApi().parseFrom(inputStream, type)
|
||||
jsonApi.parseFrom(inputStream, type)
|
||||
|
||||
/**
|
||||
* 将字节数组形式的JSON解析为指定类型的对象
|
||||
* 将字节数组形式的 JSON 解析为指定类型的对象。
|
||||
*
|
||||
* @param json 待解析的JSON字节数组
|
||||
* @param clazz 目标对象的Class类型
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型
|
||||
* @param json 待解析的 JSON 字节数组
|
||||
* @param clazz 目标对象的 [Class] 类型
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parse(json: ByteArray, clazz: Class<T>): T = getJsonApi().parse(json, clazz)
|
||||
fun <T> parse(json: ByteArray, clazz: Class<T>): T = jsonApi.parse(json, clazz)
|
||||
|
||||
/**
|
||||
* 将字节数组形式的JSON解析为指定泛型类型对象
|
||||
* 将字节数组形式的 JSON 解析为指定泛型类型的对象。
|
||||
*
|
||||
* @param json 待解析的JSON字节数组
|
||||
* @param type 目标对象的Type类型(支持泛型)
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @param T 目标对象类型
|
||||
* @param json 待解析的 JSON 字节数组
|
||||
* @param type 目标对象的 [JsonTypeReference] 类型引用(支持泛型)
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parse(json: ByteArray, type: JsonTypeReference<T>): T = getJsonApi().parse(json, type)
|
||||
fun <T> parse(json: ByteArray, type: JsonTypeReference<T>): T = jsonApi.parse(json, type)
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为指定类型的对象,解析失败时返回默认值
|
||||
* 将 JSON 字符串解析为指定类型的对象,解析失败时返回默认值。
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param clazz 目标对象的Class类型
|
||||
* @param T 目标对象类型
|
||||
* @param json 待解析的 JSON 字符串
|
||||
* @param clazz 目标对象的 [Class] 类型
|
||||
* @param defaultValue 解析失败时返回的默认值
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @return 解析后的对象实例或默认值
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parse(json: String, clazz: Class<T>, defaultValue: T): T = getJsonApi().parse(json, clazz, defaultValue)
|
||||
fun <T> parse(json: String, clazz: Class<T>, defaultValue: T): T = jsonApi.parse(json, clazz, defaultValue)
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为指定泛型类型对象,解析失败时返回默认值
|
||||
* 将 JSON 字符串解析为指定泛型类型的对象,解析失败时返回默认值。
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param type 目标对象的Type类型(支持泛型)
|
||||
* @param T 目标对象类型
|
||||
* @param json 待解析的 JSON 字符串
|
||||
* @param type 目标对象的 [JsonTypeReference] 类型引用(支持泛型)
|
||||
* @param defaultValue 解析失败时返回的默认值
|
||||
* @param <T> 泛型参数,表示目标对象的类型
|
||||
* @return 解析后的对象实例或默认值
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parse(
|
||||
json: String, type: JsonTypeReference<T>, defaultValue: T,
|
||||
): T = getJsonApi().parse(json, type, defaultValue)
|
||||
): T = jsonApi.parse(json, type, defaultValue)
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化格式的JSON字符串(带缩进和换行)
|
||||
* 将对象格式化为美化格式的 JSON 字符串(带缩进和换行)。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @return 格式化后的美化JSON字符串
|
||||
* @return 格式化后的美化 JSON 字符串
|
||||
*/
|
||||
@JvmStatic
|
||||
fun formatPretty(obj: Any): String = getJsonApi().formatPretty(obj)
|
||||
fun formatPretty(obj: Any): String = jsonApi.formatPretty(obj)
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化格式的JSON字节数组
|
||||
* 将对象格式化为美化格式的 JSON 字节数组。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @return 格式化后的美化JSON字节数组
|
||||
* @return 格式化后的美化 JSON 字节数组
|
||||
*/
|
||||
@JvmStatic
|
||||
fun formatPrettyBytes(obj: Any): ByteArray = getJsonApi().formatPrettyBytes(obj)
|
||||
fun formatPrettyBytes(obj: Any): ByteArray = jsonApi.formatPrettyBytes(obj)
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化格式的JSON字符串并写入文件
|
||||
* 将对象格式化为美化格式的 JSON 字符串并写入文件。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file 文件路径
|
||||
*/
|
||||
@JvmStatic
|
||||
fun formatPretty(obj: Any, file: String) = getJsonApi().formatPretty(obj, file)
|
||||
fun formatPretty(obj: Any, file: String) = jsonApi.formatPretty(obj, file)
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化格式的JSON字符串并写入文件
|
||||
* 将对象格式化为美化格式的 JSON 字符串并写入文件。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file Path对象
|
||||
* @param file [Path] 对象
|
||||
*/
|
||||
@JvmStatic
|
||||
fun formatPretty(obj: Any, file: Path) = getJsonApi().formatPretty(obj, file)
|
||||
fun formatPretty(obj: Any, file: Path) = jsonApi.formatPretty(obj, file)
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化格式的JSON字符串并写入文件
|
||||
* 将对象格式化为美化格式的 JSON 字符串并写入文件。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file File对象
|
||||
* @param file [File] 对象
|
||||
*/
|
||||
@JvmStatic
|
||||
fun formatPretty(obj: Any, file: File) = getJsonApi().formatPretty(obj, file)
|
||||
fun formatPretty(obj: Any, file: File) = jsonApi.formatPretty(obj, file)
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化格式的JSON字符串并写入输出流
|
||||
* 将对象格式化为美化格式的 JSON 字符串并写入输出流。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param stream OutputStream对象
|
||||
* @param stream [OutputStream] 对象
|
||||
*/
|
||||
@JvmStatic
|
||||
fun formatPretty(obj: Any, stream: OutputStream) = getJsonApi().formatPretty(obj, stream)
|
||||
|
||||
fun formatPretty(obj: Any, stream: OutputStream) = jsonApi.formatPretty(obj, stream)
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON字节数组
|
||||
* 将对象格式化为 JSON 字节数组。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @return 格式化后的JSON字节数组
|
||||
* @return 格式化后的 JSON 字节数组
|
||||
*/
|
||||
@JvmStatic
|
||||
fun formatBytes(obj: Any): ByteArray = getJsonApi().formatBytes(obj)
|
||||
|
||||
fun formatBytes(obj: Any): ByteArray = jsonApi.formatBytes(obj)
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON字符串并写入文件
|
||||
* 将对象格式化为 JSON 字符串并写入文件。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file 文件路径
|
||||
*/
|
||||
@JvmStatic
|
||||
fun format(obj: Any, file: String) = getJsonApi().format(obj, file)
|
||||
fun format(obj: Any, file: String) = jsonApi.format(obj, file)
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON字符串并写入文件
|
||||
* 将对象格式化为 JSON 字符串并写入文件。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file Path对象
|
||||
* @param file [Path] 对象
|
||||
*/
|
||||
@JvmStatic
|
||||
fun format(obj: Any, file: Path) = getJsonApi().format(obj, file)
|
||||
fun format(obj: Any, file: Path) = jsonApi.format(obj, file)
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON字符串并写入文件
|
||||
* 将对象格式化为 JSON 字符串并写入文件。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file File对象
|
||||
* @param file [File] 对象
|
||||
*/
|
||||
@JvmStatic
|
||||
fun format(obj: Any, file: File) = getJsonApi().format(obj, file)
|
||||
fun format(obj: Any, file: File) = jsonApi.format(obj, file)
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON字符串并写入输出流
|
||||
* 将对象格式化为 JSON 字符串并写入输出流。
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param stream OutputStream对象
|
||||
* @param stream [OutputStream] 对象
|
||||
*/
|
||||
@JvmStatic
|
||||
fun format(obj: Any, stream: OutputStream) = getJsonApi().format(obj, stream)
|
||||
|
||||
fun format(obj: Any, stream: OutputStream) = jsonApi.format(obj, stream)
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为指定元素类型的List集合
|
||||
* 将 JSON 字符串解析为指定元素类型的 [List] 集合。
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param elementType List中元素的类型
|
||||
* @param <T> 泛型参数,表示List中元素的类型
|
||||
* @return 解析后的List集合
|
||||
* @param T [List] 中元素的类型
|
||||
* @param json 待解析的 JSON 字符串
|
||||
* @param elementType [List] 中元素的 [Class] 类型
|
||||
* @return 解析后的 [List] 集合
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> parseList(json: String, elementType: Class<T>): List<T> = parse(json, listType(elementType))
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为指定元素类型的List集合
|
||||
* 将 JSON 字符串解析为指定元素类型的 [List] 集合。
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param <T> 泛型参数,表示List中元素的类型
|
||||
* @return 解析后的List集合
|
||||
* @param T [List] 中元素的类型,由调用方通过 reified 推断
|
||||
* @param json 待解析的 JSON 字符串
|
||||
* @return 解析后的 [List] 集合
|
||||
*/
|
||||
@JvmStatic
|
||||
inline fun <reified T> parseList(json: String): List<T> = parse(json, listType(T::class.java))
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为指定键值类型的Map集合
|
||||
* 将 JSON 字符串解析为指定键值类型的 [MutableMap] 集合。
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param keyType Map中键的类型
|
||||
* @param valueType Map中值的类型
|
||||
* @param <K> 泛型参数,表示Map中键的类型
|
||||
* @param <V> 泛型参数,表示Map中值的类型
|
||||
* @return 解析后的Map集合
|
||||
* @param K [Map] 中键的类型
|
||||
* @param V [Map] 中值的类型
|
||||
* @param json 待解析的 JSON 字符串
|
||||
* @param keyType [Map] 中键的 [Class] 类型
|
||||
* @param valueType [Map] 中值的 [Class] 类型
|
||||
* @return 解析后的 [MutableMap] 集合
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <K, V> parseMap(
|
||||
json: String, keyType: Class<K>, valueType: Class<V>,
|
||||
): MutableMap<K, V> = getJsonApi().parseMap(json, keyType, valueType)
|
||||
): MutableMap<K, V> = jsonApi.parseMap(json, keyType, valueType)
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为指定键值类型的Map集合
|
||||
* 将 JSON 字符串解析为指定键值类型的 [MutableMap] 集合。
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param <K> 泛型参数,表示Map中键的类型
|
||||
* @param <V> 泛型参数,表示Map中值的类型
|
||||
* @return 解析后的Map集合
|
||||
* @param K [Map] 中键的类型,由调用方通过 reified 推断
|
||||
* @param V [Map] 中值的类型,由调用方通过 reified 推断
|
||||
* @param json 待解析的 JSON 字符串
|
||||
* @return 解析后的 [MutableMap] 集合
|
||||
*/
|
||||
@JvmStatic
|
||||
inline fun <reified K, reified V> parseMap(
|
||||
json: String,
|
||||
): MutableMap<K, V> = getJsonApi().parseMap(json, K::class.java, V::class.java)
|
||||
): MutableMap<K, V> = jsonApi.parseMap(json, K::class.java, V::class.java)
|
||||
|
||||
/**
|
||||
* 验证字符串是否为有效的JSON格式
|
||||
* 验证字符串是否为有效的 JSON 格式。
|
||||
*
|
||||
* @param json 待验证的字符串
|
||||
* @return 如果是有效的JSON格式返回true,否则返回false
|
||||
* @return 如果是有效的 JSON 格式返回 `true`,否则返回 `false`
|
||||
*/
|
||||
@JvmStatic
|
||||
fun isValidJson(json: String): Boolean = getJsonApi().isValidJson(json)
|
||||
fun isValidJson(json: String): Boolean = jsonApi.isValidJson(json)
|
||||
|
||||
/**
|
||||
* 将对象转换为JSON字节数组
|
||||
* 将对象转换为 JSON 字节数组。
|
||||
*
|
||||
* @return 转换后的JSON字节数组
|
||||
* @param obj 待转换的对象
|
||||
* @return 转换后的 JSON 字节数组
|
||||
*/
|
||||
@JvmStatic
|
||||
fun toBytes(obj: Any): ByteArray = getJsonApi().toBytes(obj)
|
||||
fun toBytes(obj: Any): ByteArray = jsonApi.toBytes(obj)
|
||||
|
||||
/**
|
||||
* 将对象转换为美化格式的JSON字节数组
|
||||
* 将对象转换为美化格式的 JSON 字节数组。
|
||||
*
|
||||
* @return 转换后的美化格式JSON字节数组
|
||||
* @param obj 待转换的对象
|
||||
* @return 转换后的美化格式 JSON 字节数组
|
||||
*/
|
||||
@JvmStatic
|
||||
fun toBytesPretty(obj: Any): ByteArray = getJsonApi().toBytesPretty(obj)
|
||||
fun toBytesPretty(obj: Any): ByteArray = jsonApi.toBytesPretty(obj)
|
||||
|
||||
/**
|
||||
* 合并多个JSON字符串为一个JSON对象
|
||||
* 合并多个 JSON 字符串为一个 JSON 对象。
|
||||
*
|
||||
* @param jsons 待合并的JSON字符串数组
|
||||
* @return 合并后的JSON字符串
|
||||
* @param jsons 待合并的 JSON 字符串数组
|
||||
* @return 合并后的 JSON 字符串
|
||||
*/
|
||||
@JvmStatic
|
||||
fun merge(vararg jsons: String): String = getJsonApi().merge(*jsons)
|
||||
fun merge(vararg jsons: String): String = jsonApi.merge(*jsons)
|
||||
|
||||
/**
|
||||
* 获取JSON字符串中指定路径节点的值
|
||||
* 获取 JSON 字符串中指定路径节点的值。
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param path 节点路径(如:"user.name")
|
||||
* @return 节点值的字符串表示
|
||||
* @param json JSON 字符串
|
||||
* @param path 节点路径(如 `"user.name"`)
|
||||
* @return 节点值的字符串表示;节点不存在时返回 `null`
|
||||
*/
|
||||
@JvmStatic
|
||||
fun getNodeValue(json: String, path: String): String? = getJsonApi().getNodeValue(json, path)
|
||||
fun getNodeValue(json: String, path: String): String? = jsonApi.getNodeValue(json, path)
|
||||
|
||||
/**
|
||||
* 更新JSON字符串中指定路径节点的值
|
||||
* 更新 JSON 字符串中指定路径节点的值。
|
||||
*
|
||||
* @param json 原始JSON字符串
|
||||
* @param path 节点路径(如:"user.name")
|
||||
* @param json 原始 JSON 字符串
|
||||
* @param path 节点路径(如 `"user.name"`)
|
||||
* @param newValue 新的节点值
|
||||
* @return 更新后的JSON字符串
|
||||
* @return 更新后的 JSON 字符串
|
||||
*/
|
||||
@JvmStatic
|
||||
fun updateNodeValue(json: String, path: String, newValue: Any): String =
|
||||
getJsonApi().updateNodeValue(json, path, newValue)
|
||||
jsonApi.updateNodeValue(json, path, newValue)
|
||||
|
||||
/**
|
||||
* 将源对象转换为目标类型的对象
|
||||
* 将源对象转换为目标类型的对象。
|
||||
*
|
||||
* @param D 目标对象的类型
|
||||
* @param D 目标对象类型
|
||||
* @param source 需要转换的源对象
|
||||
* @param destinationClass 目标对象的Class类型
|
||||
* @param destinationClass 目标对象的 [Class] 类型
|
||||
* @return 转换后的目标类型对象
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <D> convert(source: Any, destinationClass: Class<D>): D = getJsonApi().convert(source, destinationClass)
|
||||
fun <D> convert(source: Any, destinationClass: Class<D>): D = jsonApi.convert(source, destinationClass)
|
||||
|
||||
/**
|
||||
* 使用内联函数和reified类型参数将源对象转换为目标类型的对象
|
||||
* 将源对象转换为目标类型的对象,目标类型通过 reified 推断。
|
||||
*
|
||||
* @param D 目标对象的类型(通过reified类型参数推断)
|
||||
* @param D 目标对象类型,由调用方通过 reified 推断
|
||||
* @param source 需要转换的源对象
|
||||
* @return 转换后的目标类型对象
|
||||
*/
|
||||
@JvmStatic
|
||||
inline fun <reified D> convert(source: Any): D = getJsonApi().convert(source, object : JsonTypeReference<D>() {})
|
||||
inline fun <reified D> convert(source: Any): D = jsonApi.convert(source, object : JsonTypeReference<D>() {})
|
||||
|
||||
/**
|
||||
* 将源对象转换为目标类型的对象,使用JsonTypeReference指定目标类型
|
||||
* 将源对象转换为目标类型的对象,使用 [JsonTypeReference] 指定目标类型。
|
||||
*
|
||||
* @param D 目标对象的类型
|
||||
* @param D 目标对象类型
|
||||
* @param source 需要转换的源对象
|
||||
* @param destinationType 目标对象的JsonTypeReference类型引用
|
||||
* @param destinationType 目标对象的 [JsonTypeReference] 类型引用
|
||||
* @return 转换后的目标类型对象
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <D> convert(source: Any, destinationType: JsonTypeReference<D>): D =
|
||||
getJsonApi().convert(source, destinationType)
|
||||
jsonApi.convert(source, destinationType)
|
||||
|
||||
/**
|
||||
* 添加JSON转换器到API中
|
||||
* 将当前字符串解析为指定泛型类型的对象。
|
||||
*
|
||||
* @param c 需要添加的JSON转换器实例
|
||||
* @param T 目标对象类型,由调用方通过 reified 推断
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun addJsonConverter(c: BaseJsonConverter<*, *>) = getJsonApi().addJsonConverter(c)
|
||||
|
||||
/**
|
||||
* 使用反射创建并添加指定类型的JSON转换器到API中
|
||||
*
|
||||
* @param T 继承自BaseJsonConverter的具体实现类
|
||||
*/
|
||||
inline fun <reified T : BaseJsonConverter<*, *>> addJsonConverter() = addJsonConverter(getJsonConverter<T>())
|
||||
|
||||
|
||||
inline fun <reified T> String.parseJson() = parse<T>(this)
|
||||
|
||||
/**
|
||||
* 将当前字节数组解析为指定泛型类型的对象。
|
||||
*
|
||||
* @param T 目标对象类型,由调用方通过 reified 推断
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
inline fun <reified T> ByteArray.parseJson() = parse<T>(this)
|
||||
|
||||
/**
|
||||
* 将当前 [InputStream] 的内容解析为指定泛型类型的对象,并自动关闭流。
|
||||
*
|
||||
* @param T 目标对象类型,由调用方通过 reified 推断
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
inline fun <reified T> InputStream.parseJson() = this.use { parse<T>(readBytes()) }
|
||||
|
||||
/**
|
||||
* 将当前 [File] 的内容解析为指定泛型类型的对象。
|
||||
*
|
||||
* @param T 目标对象类型,由调用方通过 reified 推断
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
inline fun <reified T> File.parseJson() = this.inputStream().parseJson<T>()
|
||||
|
||||
/**
|
||||
* 将当前 [Path] 的内容解析为指定泛型类型的对象。
|
||||
*
|
||||
* @param T 目标对象类型,由调用方通过 reified 推断
|
||||
* @return 解析后的对象实例
|
||||
*/
|
||||
inline fun <reified T> Path.parseJson() = this.toFile().inputStream().parseJson<T>()
|
||||
|
||||
/**
|
||||
* 将当前对象格式化为 JSON 字符串。
|
||||
*
|
||||
* @return 格式化后的 JSON 字符串
|
||||
*/
|
||||
fun Any.toJson() = format(this)
|
||||
|
||||
/**
|
||||
* 创建并返回一个注册了 Kotlin 模块的 Jackson [ObjectMapper]。
|
||||
*
|
||||
* @return 注册了 Kotlin 模块的 [ObjectMapper]
|
||||
*/
|
||||
@JvmStatic
|
||||
fun jacksonKotlinObjectMapper(): ObjectMapper = ObjectMapper().jacksonKotlinObjectMapper()
|
||||
|
||||
/**
|
||||
* 为当前 [ObjectMapper] 注册 Kotlin 模块并返回自身。
|
||||
*
|
||||
* @return 注册了 Kotlin 模块的 [ObjectMapper](即当前实例)
|
||||
*/
|
||||
@JvmStatic
|
||||
fun ObjectMapper.jacksonKotlinObjectMapper(): ObjectMapper = this.registerModule(kotlinModule())
|
||||
|
||||
|
||||
/**
|
||||
* 将 JSON 字符串解析为 JsonItem 对象
|
||||
* 将 JSON 字符串解析为 [JsonItem] 对象。
|
||||
*
|
||||
* @param json JSON 格式的字符串
|
||||
* @return 解析后的 JsonItem 对象,可以是 JsonObject、JsonArray 或 JsonValue
|
||||
* @return 解析后的 [JsonItem] 对象,可能是 `JsonObject`、`JsonArray` 或 `JsonValue`
|
||||
*/
|
||||
@JvmStatic
|
||||
fun parseJsonItem(json: String): JsonItem = getJsonApi().parseJsonItem(json)
|
||||
fun parseJsonItem(json: String): JsonItem = jsonApi.parseJsonItem(json)
|
||||
|
||||
/**
|
||||
* 将字节数组解析为 JsonItem 对象
|
||||
* 字节数组会被转换为字符串后再解析
|
||||
* 将字节数组解析为 [JsonItem] 对象。
|
||||
*
|
||||
* 字节数组会被转换为字符串后再解析。
|
||||
*
|
||||
* @param byte JSON 格式的字节数组(通常是 UTF-8 编码)
|
||||
* @return 解析后的 JsonItem 对象
|
||||
* @return 解析后的 [JsonItem] 对象
|
||||
*/
|
||||
@JvmStatic
|
||||
fun parseJsonItem(byte: ByteArray): JsonItem {
|
||||
@@ -562,17 +606,16 @@ object JSONA {
|
||||
}
|
||||
|
||||
/**
|
||||
* 将输入流解析为 JsonItem 对象
|
||||
* 会自动关闭输入流
|
||||
* 将输入流解析为 [JsonItem] 对象,并自动关闭输入流。
|
||||
*
|
||||
* @param inputStream JSON 数据的输入流
|
||||
* @return 解析后的 JsonItem 对象
|
||||
* @return 解析后的 [JsonItem] 对象
|
||||
* @throws IOException 当读取输入流失败时抛出
|
||||
*
|
||||
* 使用示例:
|
||||
* ```
|
||||
* val inputStream = FileInputStream("data.json")
|
||||
* val jsonItem = converter.parseJsonItem(inputStream)
|
||||
* val jsonItem = JSONA.parseJsonItem(inputStream)
|
||||
* ```
|
||||
*/
|
||||
@JvmStatic
|
||||
@@ -584,16 +627,16 @@ object JSONA {
|
||||
}
|
||||
|
||||
/**
|
||||
* 将文件解析为 JsonItem 对象
|
||||
* 将文件解析为 [JsonItem] 对象。
|
||||
*
|
||||
* @param file 包含 JSON 数据的文件
|
||||
* @return 解析后的 JsonItem 对象
|
||||
* @return 解析后的 [JsonItem] 对象
|
||||
* @throws IOException 当读取文件失败时抛出
|
||||
*
|
||||
* 使用示例:
|
||||
* ```
|
||||
* val file = File("config.json")
|
||||
* val jsonItem = converter.parseJsonItem(file)
|
||||
* val jsonItem = JSONA.parseJsonItem(file)
|
||||
* ```
|
||||
*/
|
||||
@JvmStatic
|
||||
@@ -603,16 +646,16 @@ object JSONA {
|
||||
}
|
||||
|
||||
/**
|
||||
* 将文件路径解析为 JsonItem 对象
|
||||
* 将文件路径解析为 [JsonItem] 对象。
|
||||
*
|
||||
* @param path 包含 JSON 数据的文件路径
|
||||
* @return 解析后的 JsonItem 对象
|
||||
* @return 解析后的 [JsonItem] 对象
|
||||
* @throws IOException 当读取文件失败时抛出
|
||||
*
|
||||
* 使用示例:
|
||||
* ```
|
||||
* val path = Paths.get("data/user.json")
|
||||
* val jsonItem = converter.parseJsonItem(path)
|
||||
* val jsonItem = JSONA.parseJsonItem(path)
|
||||
* ```
|
||||
*/
|
||||
@JvmStatic
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile Jackson3JsonApi.kt
|
||||
* LastUpdate 2026-10-12 13:59:59
|
||||
* LastUpdate 2026-11-17 19:59:59
|
||||
* 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.base.JsonApi
|
||||
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 tools.jackson.core.type.TypeReference
|
||||
import tools.jackson.databind.JsonNode
|
||||
@@ -36,22 +34,48 @@ import tools.jackson.databind.node.JsonNodeType
|
||||
import tools.jackson.databind.node.ObjectNode
|
||||
import java.lang.reflect.Type
|
||||
|
||||
/**
|
||||
* 基于Jackson3的JSON处理实现类,提供JSON字符串解析、格式化、合并、节点操作等功能。
|
||||
*
|
||||
* 节点路径操作([getNodeValue]、[updateNodeValue])使用JSON Pointer风格路径(如"/user/name")。
|
||||
* ObjectMapper支持直接持有,也支持通过get/set回调间接访问外部实例。
|
||||
*/
|
||||
class Jackson3JsonApi : JsonApi {
|
||||
|
||||
/**
|
||||
* ObjectMapper的获取回调,默认返回内部持有的实例
|
||||
*/
|
||||
var get: () -> ObjectMapper = { _prObjectMapper!! }
|
||||
/**
|
||||
* ObjectMapper的设置回调,默认写入内部持有的实例
|
||||
*/
|
||||
var set: (ObjectMapper) -> Unit = { _prObjectMapper = it }
|
||||
|
||||
private var _prObjectMapper: ObjectMapper? = null
|
||||
|
||||
|
||||
/**
|
||||
* 当前使用的ObjectMapper实例,读写均通过[get]/[set]回调转发
|
||||
*/
|
||||
var objectMapper: ObjectMapper
|
||||
get() = get()
|
||||
private set(value) = set(value)
|
||||
|
||||
/**
|
||||
* 使用指定的ObjectMapper构造实例
|
||||
*
|
||||
* @param objectMapper 自定义的ObjectMapper实例
|
||||
*/
|
||||
constructor(objectMapper: ObjectMapper) {
|
||||
_prObjectMapper = objectMapper
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用获取/设置回调构造实例,ObjectMapper由外部管理
|
||||
*
|
||||
* @param get ObjectMapper的获取回调
|
||||
* @param set ObjectMapper的设置回调
|
||||
*/
|
||||
constructor(
|
||||
get: () -> ObjectMapper,
|
||||
set: (ObjectMapper) -> Unit,
|
||||
@@ -60,6 +84,9 @@ class Jackson3JsonApi : JsonApi {
|
||||
this.set = set
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用默认的ObjectMapper构造实例
|
||||
*/
|
||||
constructor() {
|
||||
_prObjectMapper = ObjectMapper()
|
||||
}
|
||||
@@ -107,6 +134,9 @@ class Jackson3JsonApi : JsonApi {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并多个JSON对象字符串;无参数时返回"{}",遇到非对象JSON时抛出JsonException
|
||||
*/
|
||||
override fun merge(vararg jsons: String): String {
|
||||
try {
|
||||
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? {
|
||||
try {
|
||||
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 {
|
||||
try {
|
||||
val rootNode = objectMapper.readTree(json)
|
||||
@@ -213,12 +249,10 @@ class Jackson3JsonApi : JsonApi {
|
||||
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 {
|
||||
try {
|
||||
return getJsonItem(objectMapper.readTree(json))
|
||||
@@ -229,8 +263,21 @@ class Jackson3JsonApi : JsonApi {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 基于Jackson3的JsonItem标记实现类,通过伴生对象工厂方法创建具体的JsonItem
|
||||
*/
|
||||
class JackSon3JsonItem : JsonItem {
|
||||
/**
|
||||
* 伴生对象,提供JsonNode到JsonItem的工厂方法
|
||||
*/
|
||||
companion object {
|
||||
/**
|
||||
* 根据JsonNode的节点类型创建对应的JsonItem实例
|
||||
*
|
||||
* @param node Jackson3的JsonNode节点
|
||||
* @return 与节点类型对应的JsonItem实例
|
||||
* @throws IllegalStateException 当节点类型未知时抛出
|
||||
*/
|
||||
fun getJsonItem(node: JsonNode): JsonItem {
|
||||
return when (node.nodeType) {
|
||||
JsonNodeType.OBJECT -> JackSon3JsonObject(node)
|
||||
@@ -245,11 +292,31 @@ class JackSon3JsonItem : JsonItem {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于Jackson3节点的JSON数字类型
|
||||
*
|
||||
* @param node 数字类型的JsonNode节点
|
||||
*/
|
||||
class JackSon3JsonNumber(node: JsonNode) : JsonNumber(node.asString())
|
||||
/**
|
||||
* 基于Jackson3节点的JSON布尔类型
|
||||
*
|
||||
* @param node 布尔类型的JsonNode节点
|
||||
*/
|
||||
class JackSon3JsonBoolean(node: JsonNode) : JsonBoolean(node.asBoolean())
|
||||
/**
|
||||
* 基于Jackson3节点的JSON字符串类型
|
||||
*
|
||||
* @param node 字符串类型的JsonNode节点
|
||||
*/
|
||||
class JackSon3JsonString(node: JsonNode) : JsonString(node.asString())
|
||||
|
||||
|
||||
/**
|
||||
* 基于Jackson3节点的JSON数组类型
|
||||
*
|
||||
* @property node 数组类型的JsonNode节点
|
||||
*/
|
||||
class JackSon3JsonArray(val node: JsonNode) : JsonArray() {
|
||||
override fun getIndex(index: Int): JsonItem {
|
||||
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() {
|
||||
override fun getField(name: String): JsonItem {
|
||||
return JackSon3JsonItem.getJsonItem(node.get(name))
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile JacksonJsonApi.kt
|
||||
* LastUpdate 2026-10-12 10:48:31
|
||||
* LastUpdate 2026-11-17 19:59:59
|
||||
* 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.base.JsonApi
|
||||
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.*
|
||||
|
||||
/**
|
||||
@@ -51,6 +49,11 @@ class JacksonJsonApi : JsonApi {
|
||||
this.objectMapper = ObjectMapper()
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取内部使用的ObjectMapper实例
|
||||
*
|
||||
* @return 当前的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 {
|
||||
return try {
|
||||
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 {
|
||||
return try {
|
||||
objectMapper.writerWithDefaultPrettyPrinter().with(JsonGenerator.Feature.ESCAPE_NON_ASCII)
|
||||
@@ -289,14 +306,9 @@ class JacksonJsonApi : JsonApi {
|
||||
}
|
||||
}
|
||||
|
||||
override fun addJsonConverter(c: BaseJsonConverter<*, *>) {
|
||||
try {
|
||||
objectMapper.registerModule(c.getJacksonModule())
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to update node value", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为JsonItem对象,解析失败时包装为JsonException抛出
|
||||
*/
|
||||
override fun parseJsonItem(json: String): JsonItem {
|
||||
try {
|
||||
return getJsonItem(objectMapper.readTree(json))
|
||||
@@ -306,8 +318,21 @@ class JacksonJsonApi : JsonApi {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于Jackson2的JsonItem标记实现类,通过伴生对象工厂方法创建具体的JsonItem
|
||||
*/
|
||||
class JackSonJsonItem : JsonItem {
|
||||
/**
|
||||
* 伴生对象,提供JsonNode到JsonItem的工厂方法
|
||||
*/
|
||||
companion object {
|
||||
/**
|
||||
* 根据JsonNode的节点类型创建对应的JsonItem实例
|
||||
*
|
||||
* @param node Jackson2的JsonNode节点
|
||||
* @return 与节点类型对应的JsonItem实例
|
||||
* @throws IllegalStateException 当节点类型未知时抛出
|
||||
*/
|
||||
fun getJsonItem(node: JsonNode): JsonItem {
|
||||
return when (node.nodeType) {
|
||||
JsonNodeType.OBJECT -> JackSonJsonObject(node)
|
||||
@@ -322,11 +347,31 @@ class JackSonJsonItem : JsonItem {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于Jackson2节点的JSON数字类型
|
||||
*
|
||||
* @param node 数字类型的JsonNode节点
|
||||
*/
|
||||
class JackSonJsonNumber(node: JsonNode) : JsonNumber(node.asText())
|
||||
/**
|
||||
* 基于Jackson2节点的JSON布尔类型
|
||||
*
|
||||
* @param node 布尔类型的JsonNode节点
|
||||
*/
|
||||
class JackSonJsonBoolean(node: JsonNode) : JsonBoolean(node.asBoolean())
|
||||
/**
|
||||
* 基于Jackson2节点的JSON字符串类型
|
||||
*
|
||||
* @param node 字符串类型的JsonNode节点
|
||||
*/
|
||||
class JackSonJsonString(node: JsonNode) : JsonString(node.asText())
|
||||
|
||||
|
||||
/**
|
||||
* 基于Jackson2节点的JSON数组类型
|
||||
*
|
||||
* @property node 数组类型的JsonNode节点
|
||||
*/
|
||||
class JackSonJsonArray(val node: JsonNode) : JsonArray() {
|
||||
override fun getIndex(index: Int): JsonItem {
|
||||
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() {
|
||||
override fun getField(name: String): JsonItem {
|
||||
return getJsonItem(node.get(name))
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile JsonApi.kt
|
||||
* LastUpdate 2026-03-27 14:19:31
|
||||
* LastUpdate 2026-11-17 19:59:21
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -25,8 +25,6 @@ package com.mingliqiye.utils.json.api.base
|
||||
import com.mingliqiye.utils.exception.JsonParserException
|
||||
import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
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 okio.IOException
|
||||
import java.io.*
|
||||
@@ -40,6 +38,9 @@ import kotlin.io.path.readBytes
|
||||
*/
|
||||
interface JsonApi {
|
||||
|
||||
/**
|
||||
* 伴生对象,提供基于 reified 泛型参数的便捷解析与转换扩展函数
|
||||
*/
|
||||
companion object {
|
||||
/**
|
||||
* 将JSON字符串解析为指定泛型类型对象
|
||||
@@ -131,17 +132,6 @@ interface JsonApi {
|
||||
*/
|
||||
@JvmStatic
|
||||
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
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化格式的JSON字节数组
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @return 格式化后的美化JSON字节数组
|
||||
*/
|
||||
fun formatPrettyBytes(obj: Any): ByteArray {
|
||||
return formatPretty(obj)!!.toByteArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化JSON并写入指定路径的文件
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file 目标文件路径
|
||||
*/
|
||||
fun formatPretty(obj: Any, file: String) {
|
||||
formatPretty(obj, Paths.get(file))
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化JSON并写入指定路径的文件
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file 目标文件路径对象
|
||||
*/
|
||||
fun formatPretty(obj: Any, file: Path) {
|
||||
formatPretty(obj, file.toFile())
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化JSON并写入指定文件
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file 目标文件对象
|
||||
*/
|
||||
fun formatPretty(obj: Any, file: File) {
|
||||
FileOutputStream(file).use { fos ->
|
||||
formatPretty(obj, fos)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化JSON并写入输出流
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param stream 目标输出流
|
||||
*/
|
||||
fun formatPretty(obj: Any, stream: OutputStream) {
|
||||
stream.write(formatPrettyBytes(obj))
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON字节数组
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @return 格式化后的JSON字节数组
|
||||
*/
|
||||
fun formatBytes(obj: Any): ByteArray {
|
||||
return format(obj).toByteArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON并写入指定路径的文件
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file 目标文件路径
|
||||
*/
|
||||
fun format(obj: Any, file: String) {
|
||||
format(obj, Paths.get(file))
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON并写入指定路径的文件
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file 目标文件路径对象
|
||||
*/
|
||||
fun format(obj: Any, file: Path) {
|
||||
format(obj, file.toFile())
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON并写入指定文件
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param file 目标文件对象
|
||||
*/
|
||||
fun format(obj: Any, file: File) {
|
||||
FileOutputStream(file).use { fos ->
|
||||
format(obj, fos)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON并写入输出流
|
||||
*
|
||||
* @param obj 待格式化的对象
|
||||
* @param stream 目标输出流
|
||||
*/
|
||||
fun format(obj: Any, stream: OutputStream) {
|
||||
stream.write(formatPrettyBytes(obj))
|
||||
}
|
||||
@@ -513,20 +563,6 @@ interface JsonApi {
|
||||
*/
|
||||
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 对象
|
||||
*
|
||||
|
||||
@@ -34,6 +34,9 @@ import java.util.*
|
||||
*/
|
||||
abstract class JsonTypeReference<T> : Comparable<JsonTypeReference<T>> {
|
||||
|
||||
/**
|
||||
* 当前引用的类型信息,子类可覆写以自定义类型
|
||||
*/
|
||||
open var type: Type = Any::class.java
|
||||
|
||||
/**
|
||||
@@ -68,6 +71,12 @@ abstract class JsonTypeReference<T> : Comparable<JsonTypeReference<T>> {
|
||||
* @return 类型引用实例
|
||||
*/
|
||||
companion object {
|
||||
/**
|
||||
* 根据 reified 泛型参数创建类型引用
|
||||
*
|
||||
* @param <T> 目标类型
|
||||
* @return 类型引用实例
|
||||
*/
|
||||
inline fun <reified T> of(): JsonTypeReference<T> {
|
||||
return object : JsonTypeReference<T>() {}
|
||||
}
|
||||
|
||||
@@ -27,9 +27,15 @@ import java.lang.reflect.ParameterizedType
|
||||
import java.lang.reflect.Type
|
||||
import java.lang.reflect.WildcardType
|
||||
|
||||
/**
|
||||
* 参数化类型的简单实现,用于在运行时构造并描述带泛型参数的类型
|
||||
*
|
||||
* @property rawClass 原始类型(如 List::class.java)
|
||||
* @param paramType 泛型参数类型列表
|
||||
*/
|
||||
class TypeReference(
|
||||
val rawClass: Type,
|
||||
vararg paramType: Type
|
||||
vararg paramType: Type,
|
||||
) : ParameterizedType {
|
||||
|
||||
private val typeArguments: Array<out Type> = paramType
|
||||
@@ -40,12 +46,24 @@ class TypeReference(
|
||||
override fun getOwnerType(): Type? = null
|
||||
|
||||
|
||||
/**
|
||||
* 返回"原始类型<参数1,参数2>"形式的类型描述字符串
|
||||
*/
|
||||
override fun toString(): String = "${getRawString(rawClass)}<${
|
||||
",".join(typeArguments) { getRawString(it) }
|
||||
}>"
|
||||
|
||||
/**
|
||||
* 伴生对象,提供类型描述与TypeReference的工厂方法
|
||||
*/
|
||||
companion object {
|
||||
|
||||
/**
|
||||
* 获取类型的完整描述字符串,支持通配符与参数化类型
|
||||
*
|
||||
* @param type 类型对象
|
||||
* @return 类型的描述字符串
|
||||
*/
|
||||
fun getRawString(type: Type): String {
|
||||
return when (type) {
|
||||
is Class<*> -> type.name
|
||||
@@ -73,10 +91,23 @@ class TypeReference(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 reified 泛型参数创建TypeReference
|
||||
*
|
||||
* @param <T> 目标类型
|
||||
* @return TypeReference实例
|
||||
*/
|
||||
inline fun <reified T> of(): TypeReference {
|
||||
return of((object : JsonTypeReference<T>() {}).type)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将任意Type转换为TypeReference
|
||||
*
|
||||
* @param type 类型对象,支持Class、ParameterizedType和WildcardType
|
||||
* @return TypeReference实例
|
||||
* @throws IllegalStateException 当类型无法识别时抛出
|
||||
*/
|
||||
fun of(type: Type): TypeReference {
|
||||
return when (type) {
|
||||
is Class<*> -> TypeReference(type)
|
||||
|
||||
@@ -16,82 +16,65 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile DateTimeJsonConverter.kt
|
||||
* LastUpdate 2026-02-07 22:13:41
|
||||
* LastUpdate 2026-11-18 00:03:07
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.json.converters
|
||||
|
||||
import com.mingliqiye.utils.annotation.DateTimeJsonFormat
|
||||
import com.mingliqiye.utils.exception.JsonParserException
|
||||
import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
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.BaseJsonStringConverter
|
||||
import com.mingliqiye.utils.objects.isNull
|
||||
import com.mingliqiye.utils.string.isNullish
|
||||
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
|
||||
import com.mingliqiye.utils.json.converters.base.getAnnotation
|
||||
import com.mingliqiye.utils.json.reader.base.BaseJsonReader
|
||||
import com.mingliqiye.utils.json.witer.base.BaseJsonWriter
|
||||
import com.mingliqiye.utils.time.DateTime
|
||||
import com.mingliqiye.utils.time.Formatter
|
||||
|
||||
|
||||
/**
|
||||
* DateTimeJsonConverter 是一个用于处理 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 字符串。
|
||||
* [DateTime] 的 JSON 字符串转换器。
|
||||
*
|
||||
* @param obj 需要转换的 DateTime 对象,可能为 null。
|
||||
* @param annotationGetter 用于获取注解信息的对象,用于决定格式化方式。
|
||||
* @return 转换后的字符串,如果输入为 null 则返回 null。
|
||||
* @throws Exception 如果在转换过程中发生异常。
|
||||
* 根据字段上的 [DateTimeJsonFormat] 注解选择格式化器,
|
||||
* 在日期时间对象与 JSON 字符串之间进行双向转换。
|
||||
*/
|
||||
class DateTimeJsonConverter : BaseJsonConverter<DateTime> {
|
||||
/**
|
||||
* 按 [DateTimeJsonFormat] 注解指定的格式将日期时间写为 JSON 字符串,null 时写入 null
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun convert(obj: DateTime?, annotationGetter: AnnotationGetter): String? {
|
||||
// 如果输入对象为 null,直接返回 null
|
||||
if (obj.isNull()) return null
|
||||
|
||||
// 获取 DateTimeJsonFormat 注解信息
|
||||
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.get<DateTimeJsonFormat>()
|
||||
|
||||
// 根据注解中的格式化规则进行转换
|
||||
return if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) {
|
||||
override fun convert(
|
||||
obj: DateTime?,
|
||||
jsonWriter: BaseJsonWriter,
|
||||
annotationGetter: AnnotationGetter,
|
||||
) {
|
||||
if (obj == null) {
|
||||
jsonWriter.setNull()
|
||||
return
|
||||
}
|
||||
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.getAnnotation<DateTimeJsonFormat>()
|
||||
val value = if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) {
|
||||
obj.format(dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero)
|
||||
} else if (dateTimeJsonFormat?.formatter?.isEmpty() == false) {
|
||||
obj.format(dateTimeJsonFormat.formatter, dateTimeJsonFormat.repcZero)
|
||||
} else {
|
||||
obj.format()
|
||||
}
|
||||
jsonWriter.setString(value)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将 JSON 字符串转换为 DateTime 对象。
|
||||
* 按 [DateTimeJsonFormat] 注解指定的格式从 JSON 字符串解析日期时间
|
||||
*
|
||||
* @param obj 需要转换的字符串,可能为 null 或空。
|
||||
* @param annotationGetter 用于获取注解信息的对象,用于决定解析方式。
|
||||
* @return 解析后的 DateTime 对象,如果输入为 null 或空则返回 null。
|
||||
* @throws Exception 如果在解析过程中发生异常。
|
||||
* @throws JsonParserException 当节点不是字符串类型时抛出
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun deConvert(obj: String?, annotationGetter: AnnotationGetter): DateTime? {
|
||||
// 如果输入字符串为 null 或空,直接返回 null
|
||||
if (obj.isNullish()) return null
|
||||
|
||||
// 获取 DateTimeJsonFormat 注解信息
|
||||
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.get<DateTimeJsonFormat>()
|
||||
|
||||
// 根据注解中的解析规则进行转换
|
||||
override fun deConvert(jsonReader: BaseJsonReader, annotationGetter: AnnotationGetter): DateTime? {
|
||||
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.getAnnotation<DateTimeJsonFormat>()
|
||||
if (jsonReader.isNull) return null
|
||||
if (!jsonReader.isString) throw JsonParserException("type item not string")
|
||||
val obj = jsonReader.getString()
|
||||
return if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) {
|
||||
DateTime.parse(obj, dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero)
|
||||
} else if (dateTimeJsonFormat?.formatter?.isEmpty() == false) {
|
||||
@@ -101,12 +84,5 @@ class DateTimeJsonConverter private constructor() : BaseJsonStringConverter<Date
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前转换器支持的目标类型引用。
|
||||
*
|
||||
* @return 返回 DateTime 类型的 JsonTypeReference。
|
||||
* @throws Exception 如果在获取类型引用时发生异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getFromType(): JsonTypeReference<DateTime> = JsonTypeReference.of<DateTime>()
|
||||
override fun getType(): JsonTypeReference<DateTime> = JsonTypeReference.of<DateTime>()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* 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 NetworkEndpointJsonConverter.kt
|
||||
* LastUpdate 2026-11-18 00:03:17
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.json.converters
|
||||
|
||||
import com.mingliqiye.utils.exception.JsonParserException
|
||||
import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
|
||||
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
|
||||
|
||||
/**
|
||||
* [NetworkEndpoint] 的 JSON 字符串转换器。
|
||||
*
|
||||
* 继承 [BaseJsonStringConverter],负责在网络端点对象与 JSON 字符串之间进行转换:
|
||||
* 序列化时输出形如 `host:port` 的字符串,反序列化时将 `host:port` 字符串还原为
|
||||
* [NetworkEndpoint] 实例。
|
||||
*
|
||||
* 本类为单例:构造器私有,通过 [getJsonConverter] 获取全局共享实例,
|
||||
* 避免在序列化框架中重复创建。
|
||||
*
|
||||
* @see BaseJsonStringConverter
|
||||
* @see NetworkEndpoint
|
||||
*/
|
||||
class NetworkEndpointJsonConverter : BaseJsonConverter<NetworkEndpoint> {
|
||||
/**
|
||||
* 将网络端点写为 `host:port` 形式的 JSON 字符串,null 时写入 null
|
||||
*/
|
||||
override fun convert(
|
||||
obj: NetworkEndpoint?,
|
||||
jsonWriter: BaseJsonWriter,
|
||||
annotationGetter: AnnotationGetter,
|
||||
) {
|
||||
if (obj == null) jsonWriter.setNull() else jsonWriter.setString(obj.toHostPortString())
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 `host:port` 形式的 JSON 字符串还原网络端点
|
||||
*
|
||||
* @throws JsonParserException 当节点不是字符串类型时抛出
|
||||
*/
|
||||
override fun deConvert(
|
||||
jsonReader: BaseJsonReader,
|
||||
annotationGetter: AnnotationGetter,
|
||||
): NetworkEndpoint? {
|
||||
return if (jsonReader.isNotNull) {
|
||||
if (!jsonReader.isString) throw JsonParserException("type item not string")
|
||||
NetworkEndpoint.of(jsonReader.getString())
|
||||
} else null
|
||||
}
|
||||
|
||||
override fun getType(): JsonTypeReference<NetworkEndpoint> = JsonTypeReference.of()
|
||||
}
|
||||
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile UUIDJsonConverter.kt
|
||||
* LastUpdate 2026-02-08 01:37:00
|
||||
* LastUpdate 2026-11-18 00:03:17
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -24,76 +24,66 @@ package com.mingliqiye.utils.json.converters
|
||||
|
||||
import com.mingliqiye.utils.annotation.UUIDJsonFormat
|
||||
import com.mingliqiye.utils.base.BaseType
|
||||
import com.mingliqiye.utils.exception.JsonParserException
|
||||
import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
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.BaseJsonStringConverter
|
||||
import com.mingliqiye.utils.objects.isNull
|
||||
import com.mingliqiye.utils.string.isNullish
|
||||
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
|
||||
import com.mingliqiye.utils.json.converters.base.getAnnotation
|
||||
import com.mingliqiye.utils.json.reader.base.BaseJsonReader
|
||||
import com.mingliqiye.utils.json.witer.base.BaseJsonWriter
|
||||
import com.mingliqiye.utils.uuid.UUID
|
||||
import com.mingliqiye.utils.uuid.UUIDFormatType
|
||||
|
||||
/**
|
||||
* UUIDJsonConverter 是一个用于处理 UUID 类型与 JSON 字符串之间转换的类。
|
||||
* 它继承自 BaseJsonStringConverter,并实现了 convert 和 deConvert 方法,
|
||||
* 分别用于将 UUID 对象序列化为字符串以及反序列化字符串为 UUID 对象。
|
||||
* [UUID] 的 JSON 字符串转换器。
|
||||
*
|
||||
* 根据字段上的 [UUIDJsonFormat] 注解选择进制与格式,
|
||||
* 在 UUID 对象与 JSON 字符串之间进行双向转换。
|
||||
*/
|
||||
class UUIDJsonConverter private constructor() : BaseJsonStringConverter<UUID> {
|
||||
|
||||
companion object {
|
||||
private val uuidJsonConverter by lazy {
|
||||
UUIDJsonConverter()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun getJsonConverter(): UUIDJsonConverter = uuidJsonConverter
|
||||
}
|
||||
class UUIDJsonConverter : BaseJsonConverter<UUID> {
|
||||
|
||||
/**
|
||||
* 将 UUID 对象转换为字符串形式。
|
||||
*
|
||||
* @param obj 需要转换的 UUID 对象,可能为 null。
|
||||
* @param annotationGetter 用于获取注解信息的对象。
|
||||
* @return 转换后的字符串,如果输入为 null 则返回 null。
|
||||
* 按 [UUIDJsonFormat] 注解指定的进制与格式将 UUID 写为 JSON 字符串,null 时写入 null
|
||||
*/
|
||||
override fun convert(
|
||||
obj: UUID?,
|
||||
annotationGetter: AnnotationGetter
|
||||
): String? {
|
||||
// 如果输入对象为 null,直接返回 null
|
||||
if (obj.isNull()) return null
|
||||
jsonWriter: BaseJsonWriter,
|
||||
annotationGetter: AnnotationGetter,
|
||||
) {
|
||||
if (obj == null) {
|
||||
jsonWriter.setNull()
|
||||
return
|
||||
}
|
||||
val dateTimeJsonFormat: UUIDJsonFormat? = annotationGetter.getAnnotation<UUIDJsonFormat>()
|
||||
|
||||
// 获取 UUIDJsonFormat 注解信息,若未找到则使用默认格式
|
||||
val dateTimeJsonFormat: UUIDJsonFormat = annotationGetter.get<UUIDJsonFormat>() ?: return obj.getString()
|
||||
|
||||
// 根据注解中的 base 和 value 属性选择合适的字符串表示方式
|
||||
return if (BaseType.BASE16 != dateTimeJsonFormat.base) {
|
||||
val uuid =
|
||||
if (dateTimeJsonFormat == null) obj.getString() else if (BaseType.BASE16 != dateTimeJsonFormat.base) {
|
||||
obj.getString(dateTimeJsonFormat.base)
|
||||
} else if (UUIDFormatType.NO_UPPER_SPACE != dateTimeJsonFormat.value) {
|
||||
obj.getString(dateTimeJsonFormat.value)
|
||||
} else {
|
||||
obj.getString()
|
||||
}
|
||||
|
||||
jsonWriter.setString(uuid)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字符串反序列化为 UUID 对象。
|
||||
* 按 [UUIDJsonFormat] 注解指定的进制从 JSON 字符串解析 UUID
|
||||
*
|
||||
* @param obj 需要反序列化的字符串,可能为 null 或空。
|
||||
* @param annotationGetter 用于获取注解信息的对象。
|
||||
* @return 反序列化后的 UUID 对象,如果输入无效则返回 null。
|
||||
* @throws JsonParserException 当节点不是字符串类型时抛出
|
||||
*/
|
||||
override fun deConvert(
|
||||
obj: String?,
|
||||
annotationGetter: AnnotationGetter
|
||||
jsonReader: BaseJsonReader,
|
||||
annotationGetter: AnnotationGetter,
|
||||
): UUID? {
|
||||
// 如果输入字符串为 null 或空,直接返回 null
|
||||
if (obj.isNullish()) return null
|
||||
if (jsonReader.isNull) return null
|
||||
if (!jsonReader.isString) throw JsonParserException("type item not string")
|
||||
|
||||
// 获取 UUIDJsonFormat 注解信息,若未找到则使用默认解析方式
|
||||
val dateTimeJsonFormat: UUIDJsonFormat = annotationGetter.get<UUIDJsonFormat>() ?: return UUID.of(obj)
|
||||
val obj = jsonReader.getString()
|
||||
|
||||
// 根据注解中的 base 属性选择合适的解析方式
|
||||
val dateTimeJsonFormat: UUIDJsonFormat = annotationGetter.getAnnotation<UUIDJsonFormat>() ?: return UUID.of(obj)
|
||||
return if (BaseType.BASE16 != dateTimeJsonFormat.base) {
|
||||
UUID.of(obj, dateTimeJsonFormat.base)
|
||||
} else {
|
||||
@@ -101,10 +91,5 @@ class UUIDJsonConverter private constructor() : BaseJsonStringConverter<UUID> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回当前转换器支持的目标类型引用。
|
||||
*
|
||||
* @return 表示 UUID 类型的 JsonTypeReference 对象。
|
||||
*/
|
||||
override fun getFromType() = JsonTypeReference.of<UUID>()
|
||||
override fun getType(): JsonTypeReference<UUID> = JsonTypeReference.of()
|
||||
}
|
||||
|
||||
@@ -16,67 +16,21 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile AnnotationGetter.kt
|
||||
* LastUpdate 2026-03-11 08:46:40
|
||||
* LastUpdate 2026-11-17 19:46:16
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.json.converters.base
|
||||
|
||||
/**
|
||||
* 定义一个用于获取注解的接口。
|
||||
* 提供了一个通用方法来根据注解类型获取对应的注解实例。
|
||||
* 注解获取接口,用于在自定义序列化/反序列化时读取字段上的注解
|
||||
*/
|
||||
interface AnnotationGetter {
|
||||
/**
|
||||
* 根据指定的注解类型获取该类型的注解实例。
|
||||
* 获取指定类型的注解
|
||||
*
|
||||
* @param clazz 注解的Class对象,表示要获取的注解类型。
|
||||
* @return 返回对应类型的注解实例,如果未找到则返回null。
|
||||
* @param clazz 注解的Class类型
|
||||
* @return 注解实例,不存在时返回null(默认实现始终返回null)
|
||||
*/
|
||||
fun <T : Annotation> get(clazz: Class<T>): T?
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
}
|
||||
fun <T : Annotation> getAnnotation(clazz: Class<T>): T? = null
|
||||
}
|
||||
|
||||
-49
@@ -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>()
|
||||
}
|
||||
-45
@@ -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
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile BaseJsonConverter.kt
|
||||
* LastUpdate 2026-02-26 15:59:35
|
||||
* LastUpdate 2026-11-17 20:10:50
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
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 定义了转换的源类型和目标类型。
|
||||
* 实现该接口的类需要提供具体的 JSON 转换逻辑。
|
||||
*
|
||||
* @param F 源类型,表示需要被转换的数据类型。
|
||||
* @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>()
|
||||
}
|
||||
+31
-13
@@ -16,32 +16,50 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile JackJson3Deserializer.kt
|
||||
* LastUpdate 2026-02-26 13:02:52
|
||||
* LastUpdate 2026-11-17 19:51:20
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.json.converters.base
|
||||
|
||||
import com.mingliqiye.utils.json.reader.JackSon3JsonReader
|
||||
import tools.jackson.core.JsonParser
|
||||
import tools.jackson.core.JsonToken
|
||||
import tools.jackson.databind.BeanProperty
|
||||
import tools.jackson.databind.DeserializationContext
|
||||
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 jsonConverter: JsonConverter<F, T>
|
||||
) : ValueDeserializer<F>() {
|
||||
val jsonConverter: BaseJsonConverter<T>,
|
||||
) : 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(
|
||||
p: JsonParser,
|
||||
ctxt: DeserializationContext?
|
||||
): F? {
|
||||
if (p.currentToken() == JsonToken.VALUE_NULL) return null
|
||||
return jsonConverter.deConvert(p.readValueAs(jsonConverter.getToClass()), object : AnnotationGetter {
|
||||
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
|
||||
})
|
||||
ctxt: DeserializationContext?,
|
||||
): T? {
|
||||
return jsonConverter.deConvert(JackSon3JsonReader(p.readValueAsTree()), annotationGetter)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,8 +71,8 @@ class JackJson3Deserializer<F, T>(
|
||||
*/
|
||||
override fun createContextual(
|
||||
ctxt: DeserializationContext?,
|
||||
property: BeanProperty?
|
||||
): JackJson3Deserializer<F, T> {
|
||||
property: BeanProperty?,
|
||||
): JackJson3Deserializer<T> {
|
||||
return JackJson3Deserializer(property, jsonConverter)
|
||||
}
|
||||
|
||||
|
||||
@@ -16,50 +16,56 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile JackJson3Serializer.kt
|
||||
* LastUpdate 2026-02-26 13:04:18
|
||||
* LastUpdate 2026-11-17 19:51:33
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
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.SerializationContext
|
||||
import tools.jackson.databind.ValueSerializer
|
||||
import java.math.BigDecimal
|
||||
import java.math.BigInteger
|
||||
|
||||
class JackJson3Serializer<F, T>(
|
||||
|
||||
/**
|
||||
* Jackson3 序列化适配器,将 [BaseJsonConverter] 包装为 Jackson3 的 [ValueSerializer]。
|
||||
*
|
||||
* @property property 当前属性信息,用于读取字段注解,可为null
|
||||
* @property jsonConverter 实际执行序列化逻辑的转换器
|
||||
*/
|
||||
class JackJson3Serializer<T>(
|
||||
val property: BeanProperty? = null,
|
||||
val jsonConverter: JsonConverter<F, T>
|
||||
) : ValueSerializer<F>() {
|
||||
val jsonConverter: BaseJsonConverter<T>,
|
||||
) : ValueSerializer<T>() {
|
||||
|
||||
/**
|
||||
* 序列化方法:将源对象转换为目标对象,并根据目标对象的类型写入 JSON。
|
||||
*
|
||||
* @param value 源对象,可能为 null。
|
||||
* @param gen JSON 生成器,用于写入 JSON 数据。
|
||||
* @param provider 序列化提供者,可选参数。
|
||||
* 注解获取器,从当前属性信息中读取字段注解
|
||||
*/
|
||||
override fun serialize(value: F, gen: tools.jackson.core.JsonGenerator, ctxt: SerializationContext) {
|
||||
val data: T? = jsonConverter.convert(value, object : AnnotationGetter {
|
||||
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
|
||||
})
|
||||
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")
|
||||
}
|
||||
val annotationGetter =
|
||||
object : AnnotationGetter {
|
||||
override fun <T : Annotation> getAnnotation(clazz: Class<T>): T? = property?.getAnnotation(clazz)
|
||||
}
|
||||
|
||||
/**
|
||||
* 序列化方法:将源对象交给转换器写入 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<*> {
|
||||
return JackJson3Serializer(property, jsonConverter)
|
||||
}
|
||||
|
||||
@@ -16,31 +16,51 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile JackJsonDeserializer.kt
|
||||
* LastUpdate 2026-02-08 02:22:46
|
||||
* LastUpdate 2026-11-17 19:53:29
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.json.converters.base
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser
|
||||
import com.fasterxml.jackson.core.JsonToken
|
||||
import com.fasterxml.jackson.databind.BeanProperty
|
||||
import com.fasterxml.jackson.databind.DeserializationContext
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer
|
||||
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 jsonConverter: JsonConverter<F, T>
|
||||
) : JsonDeserializer<F>(), ContextualDeserializer {
|
||||
val jsonConverter: BaseJsonConverter<T>,
|
||||
) : 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(
|
||||
p: JsonParser,
|
||||
ctxt: DeserializationContext?
|
||||
): F? {
|
||||
if (p.currentToken == JsonToken.VALUE_NULL) return null
|
||||
return jsonConverter.deConvert(p.readValueAs(jsonConverter.getToClass()), object : AnnotationGetter {
|
||||
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
|
||||
})
|
||||
ctxt: DeserializationContext?,
|
||||
): T? {
|
||||
return jsonConverter.deConvert(JackSonJsonReader(p.readValueAsTree()), annotationGetter)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -48,12 +68,12 @@ class JackJsonDeserializer<F, T>(
|
||||
*
|
||||
* @param ctxt 反序列化上下文,可选参数。
|
||||
* @param property 当前属性信息。
|
||||
* @return 返回当前反序列化器实例。
|
||||
* @return 携带属性信息的新反序列化器实例。
|
||||
*/
|
||||
override fun createContextual(
|
||||
ctxt: DeserializationContext?,
|
||||
property: BeanProperty?
|
||||
): JackJsonDeserializer<F, T> {
|
||||
property: BeanProperty?,
|
||||
): JackJsonDeserializer<T> {
|
||||
return JackJsonDeserializer(property, jsonConverter)
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user