feat(network): 添加网络地址和端口相关工具类
- 新增 NetworkAddress 类用于表示网络地址,支持 IPv4 和 IPv6 - 新增 NetworkPort 类用于表示端口号 - 新增 NetworkEndpoint 类用于封装网络地址和端口信息 - 优化 AutoConfiguration 类,添加更多系统信息 - 更新 AesUtils、Base64Utils等类的版本信息 - 删除 Minecraft SLF 相关无用代码 - 更新项目版本号至 4.0.7
This commit is contained in:
@@ -0,0 +1,231 @@
|
||||
/*
|
||||
* Copyright 2025 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 GsonJsonApi.kt
|
||||
* LastUpdate 2025-09-15 22:07:43
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.json
|
||||
|
||||
import com.google.gson.*
|
||||
import com.mingliqiye.utils.json.converters.JsonConverter
|
||||
import com.mingliqiye.utils.json.converters.JsonStringConverter
|
||||
|
||||
class GsonJsonApi : JsonApi {
|
||||
|
||||
private var gsonUnicode: Gson
|
||||
private var gsonPretty: Gson
|
||||
private var gsonPrettyUnicode: Gson
|
||||
private var gson: Gson
|
||||
|
||||
constructor() {
|
||||
gson = GsonBuilder()
|
||||
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
||||
.create()
|
||||
|
||||
gsonUnicode = GsonBuilder()
|
||||
.disableHtmlEscaping()
|
||||
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
||||
.create()
|
||||
|
||||
gsonPretty = GsonBuilder()
|
||||
.setPrettyPrinting()
|
||||
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
||||
.create()
|
||||
|
||||
gsonPrettyUnicode = GsonBuilder()
|
||||
.setPrettyPrinting()
|
||||
.disableHtmlEscaping()
|
||||
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
||||
.create()
|
||||
}
|
||||
|
||||
constructor(gson: Gson) {
|
||||
this.gson = gson
|
||||
.newBuilder()
|
||||
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
||||
.create()
|
||||
this.gsonUnicode = gson
|
||||
.newBuilder()
|
||||
.disableHtmlEscaping()
|
||||
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
||||
.create()
|
||||
this.gsonPretty = gson
|
||||
.newBuilder()
|
||||
.setPrettyPrinting()
|
||||
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
||||
.create()
|
||||
this.gsonPrettyUnicode = gson
|
||||
.newBuilder()
|
||||
.setPrettyPrinting()
|
||||
.disableHtmlEscaping()
|
||||
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
||||
.create()
|
||||
}
|
||||
|
||||
override fun <T> parse(json: String, clazz: Class<T>): T {
|
||||
return gson.fromJson(json, clazz)
|
||||
}
|
||||
|
||||
override fun <T> parse(json: String, type: JsonTypeReference<T>): T {
|
||||
return gson.fromJson(json, type.type)
|
||||
}
|
||||
|
||||
override fun format(obj: Any): String {
|
||||
return gson.toJson(obj)
|
||||
}
|
||||
|
||||
override fun formatUnicode(obj: Any): String {
|
||||
return gsonUnicode.toJson(obj)
|
||||
}
|
||||
|
||||
override fun formatPretty(obj: Any): String {
|
||||
return gsonPretty.toJson(obj)
|
||||
}
|
||||
|
||||
override fun formatPrettyUnicode(obj: Any): String {
|
||||
return gsonPrettyUnicode.toJson(obj)
|
||||
}
|
||||
|
||||
override fun isValidJson(json: String): Boolean {
|
||||
return try {
|
||||
JsonParser.parseString(json)
|
||||
true
|
||||
} catch (e: JsonSyntaxException) {
|
||||
false
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
override fun merge(vararg jsons: String): String {
|
||||
val merged = JsonObject()
|
||||
for (json in jsons) {
|
||||
if (json.isNullOrEmpty()) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
val obj = JsonParser.parseString(json).asJsonObject
|
||||
for (key in obj.keySet()) {
|
||||
merged.add(key, obj.get(key))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// 忽略无效的 JSON 字符串
|
||||
}
|
||||
}
|
||||
return gson.toJson(merged)
|
||||
}
|
||||
|
||||
override fun getNodeValue(json: String, path: String): String? {
|
||||
return try {
|
||||
var element = JsonParser.parseString(json)
|
||||
val paths = path.split("\\.".toRegex()).toTypedArray()
|
||||
var current = element
|
||||
|
||||
for (p in paths) {
|
||||
if (current.isJsonObject) {
|
||||
current = current.asJsonObject.get(p)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
|
||||
if (current == null) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
if (current.isJsonPrimitive) current.asString else current.toString()
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override fun updateNodeValue(json: String, path: String, newValue: Any): String {
|
||||
return try {
|
||||
val obj = JsonParser.parseString(json).asJsonObject
|
||||
val paths = path.split("\\.".toRegex()).toTypedArray()
|
||||
var current = obj
|
||||
|
||||
// 导航到倒数第二层
|
||||
for (i in 0 until paths.size - 1) {
|
||||
val p = paths[i]
|
||||
if (!current.has(p) || !current.get(p).isJsonObject) {
|
||||
current.add(p, JsonObject())
|
||||
}
|
||||
current = current.getAsJsonObject(p)
|
||||
}
|
||||
|
||||
// 设置最后一层的值
|
||||
val lastPath = paths[paths.size - 1]
|
||||
val element = gson.toJsonTree(newValue)
|
||||
current.add(lastPath, element)
|
||||
|
||||
gson.toJson(obj)
|
||||
} catch (e: Exception) {
|
||||
json
|
||||
}
|
||||
}
|
||||
|
||||
override fun <T, D> convert(source: T, destinationClass: Class<D>): D {
|
||||
val json = gson.toJson(source)
|
||||
return gson.fromJson(json, destinationClass)
|
||||
}
|
||||
|
||||
override fun <T, D> convert(source: T, destinationType: JsonTypeReference<D>): D {
|
||||
val json = gson.toJson(source)
|
||||
return gson.fromJson(json, destinationType.type)
|
||||
}
|
||||
|
||||
override fun addJsonConverter(c: JsonConverter<*, *>) {
|
||||
c.getStringConverter()?.let {
|
||||
gson = gson
|
||||
.newBuilder()
|
||||
.registerTypeAdapter(
|
||||
it.tClass,
|
||||
it.gsonJsonStringConverterAdapter
|
||||
)
|
||||
.create()
|
||||
gsonUnicode = gsonUnicode
|
||||
.newBuilder()
|
||||
.registerTypeAdapter(
|
||||
it.tClass,
|
||||
it.gsonJsonStringConverterAdapter
|
||||
)
|
||||
.create()
|
||||
gsonPretty = gsonPretty
|
||||
.newBuilder()
|
||||
.registerTypeAdapter(
|
||||
it.tClass,
|
||||
it.gsonJsonStringConverterAdapter
|
||||
)
|
||||
.create()
|
||||
gsonPrettyUnicode = gsonPrettyUnicode
|
||||
.newBuilder()
|
||||
.registerTypeAdapter(
|
||||
it.tClass,
|
||||
it.gsonJsonStringConverterAdapter
|
||||
)
|
||||
.create()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
override fun addJsonStringConverter(c: JsonStringConverter<*>) {
|
||||
addJsonConverter(c)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
/*
|
||||
* Copyright 2025 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 JacksonJsonApi.kt
|
||||
* LastUpdate 2025-09-15 22:07:43
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.json
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator
|
||||
import com.fasterxml.jackson.core.JsonProcessingException
|
||||
import com.fasterxml.jackson.databind.JsonNode
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import com.fasterxml.jackson.databind.ObjectReader
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode
|
||||
import com.mingliqiye.utils.json.converters.JsonConverter
|
||||
import com.mingliqiye.utils.json.converters.JsonStringConverter
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* 基于Jackson的JSON处理实现类,提供JSON字符串解析、格式化、合并、节点操作等功能。
|
||||
*/
|
||||
class JacksonJsonApi : JsonApi {
|
||||
|
||||
private val objectMapper: ObjectMapper
|
||||
|
||||
/**
|
||||
* 使用默认的ObjectMapper构造实例
|
||||
*/
|
||||
constructor() {
|
||||
this.objectMapper = ObjectMapper()
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用指定的ObjectMapper构造实例
|
||||
*
|
||||
* @param objectMapper 自定义的ObjectMapper实例
|
||||
*/
|
||||
constructor(objectMapper: ObjectMapper) {
|
||||
this.objectMapper = objectMapper.copy()
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为指定类型的对象
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param clazz 目标对象类型
|
||||
* @param <T> 泛型参数,表示目标对象类型
|
||||
* @return 解析后的对象
|
||||
* @throws JsonException 当解析失败时抛出异常
|
||||
*/
|
||||
override fun <T> parse(json: String, clazz: Class<T>): T {
|
||||
return try {
|
||||
objectMapper.readValue(json, clazz)
|
||||
} catch (e: IOException) {
|
||||
throw JsonException("Failed to parse JSON string", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为复杂泛型结构的对象(如List、Map等)
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param type 泛型类型引用
|
||||
* @param <T> 泛型参数,表示目标对象类型
|
||||
* @return 解析后的对象
|
||||
* @throws JsonException 当解析失败时抛出异常
|
||||
*/
|
||||
override fun <T> parse(json: String, type: JsonTypeReference<T>): T {
|
||||
return try {
|
||||
val reader: ObjectReader = objectMapper.readerFor(
|
||||
objectMapper.constructType(type.type)
|
||||
)
|
||||
reader.readValue(json)
|
||||
} catch (e: IOException) {
|
||||
throw JsonException("Failed to parse JSON string", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON字符串
|
||||
*
|
||||
* @param `object` 待格式化的对象
|
||||
* @return 格式化后的JSON字符串
|
||||
* @throws JsonException 当格式化失败时抛出异常
|
||||
*/
|
||||
override fun format(obj: Any): String {
|
||||
return try {
|
||||
objectMapper.writeValueAsString(obj)
|
||||
} catch (e: JsonProcessingException) {
|
||||
throw JsonException(
|
||||
"Failed to format object to JSON string",
|
||||
e
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun formatUnicode(obj: Any): String {
|
||||
return try {
|
||||
objectMapper
|
||||
.writer()
|
||||
.with(JsonGenerator.Feature.ESCAPE_NON_ASCII)
|
||||
.writeValueAsString(obj)
|
||||
} catch (e: JsonProcessingException) {
|
||||
throw JsonException(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化(带缩进)的JSON字符串
|
||||
*
|
||||
* @param `object` 待格式化的对象
|
||||
* @return 美化后的JSON字符串
|
||||
* @throws JsonException 当格式化失败时抛出异常
|
||||
*/
|
||||
override fun formatPretty(obj: Any): String {
|
||||
return try {
|
||||
objectMapper
|
||||
.writerWithDefaultPrettyPrinter()
|
||||
.writeValueAsString(obj)
|
||||
} catch (e: JsonProcessingException) {
|
||||
throw JsonException(
|
||||
"Failed to format object to pretty JSON string",
|
||||
e
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun formatPrettyUnicode(obj: Any): String {
|
||||
return try {
|
||||
objectMapper
|
||||
.writerWithDefaultPrettyPrinter()
|
||||
.with(JsonGenerator.Feature.ESCAPE_NON_ASCII)
|
||||
.writeValueAsString(obj)
|
||||
} catch (e: JsonProcessingException) {
|
||||
throw JsonException(
|
||||
"Failed to format object to pretty JSON string",
|
||||
e
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 判断给定字符串是否是有效的JSON格式
|
||||
*
|
||||
* @param json 待验证的字符串
|
||||
* @return 如果是有效JSON返回true,否则返回false
|
||||
*/
|
||||
override fun isValidJson(json: String): Boolean {
|
||||
return try {
|
||||
objectMapper.readTree(json)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并多个JSON字符串为一个JSON对象
|
||||
*
|
||||
* @param jsons 多个JSON字符串
|
||||
* @return 合并后的JSON字符串
|
||||
* @throws JsonException 当合并失败时抛出异常
|
||||
*/
|
||||
override fun merge(vararg jsons: String): String {
|
||||
val result: ObjectNode = objectMapper.createObjectNode()
|
||||
for (json in jsons) {
|
||||
try {
|
||||
val node: JsonNode = objectMapper.readTree(json)
|
||||
if (node.isObject) {
|
||||
result.setAll<JsonNode>(node as ObjectNode)
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
// 忽略无效的JSON字符串
|
||||
}
|
||||
}
|
||||
return try {
|
||||
objectMapper.writeValueAsString(result)
|
||||
} catch (e: JsonProcessingException) {
|
||||
throw JsonException("Failed to merge JSON strings", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取JSON字符串中指定路径的节点值
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param path 节点路径,使用"."分隔
|
||||
* @return 节点值的文本表示,如果路径不存在则返回null
|
||||
* @throws JsonException 当获取节点值失败时抛出异常
|
||||
*/
|
||||
override fun getNodeValue(json: String, path: String): String? {
|
||||
return try {
|
||||
var node: JsonNode = objectMapper.readTree(json)
|
||||
val paths: Array<String> = path.split("\\.".toRegex()).toTypedArray()
|
||||
for (p in paths) {
|
||||
node = node.get(p)
|
||||
}
|
||||
node.asText()
|
||||
} catch (e: IOException) {
|
||||
throw JsonException("Failed to get node value", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新JSON字符串中指定路径的节点值
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param path 节点路径,使用"."分隔
|
||||
* @param newValue 新的节点值
|
||||
* @return 更新后的JSON字符串
|
||||
* @throws JsonException 当更新节点值失败时抛出异常
|
||||
*/
|
||||
override fun updateNodeValue(json: String, path: String, newValue: Any): String {
|
||||
return try {
|
||||
val node: JsonNode = objectMapper.readTree(json)
|
||||
if (node is ObjectNode) {
|
||||
val objectNode: ObjectNode = node
|
||||
val paths: Array<String> = path.split("\\.".toRegex()).toTypedArray()
|
||||
var current: JsonNode = objectNode
|
||||
|
||||
// 导航到目标节点的父节点
|
||||
for (i in 0 until paths.size - 1) {
|
||||
current = current.get(paths[i])
|
||||
if (current !is ObjectNode) {
|
||||
return json // 路径不存在或无效
|
||||
}
|
||||
}
|
||||
|
||||
// 更新值
|
||||
if (current is ObjectNode) {
|
||||
val parent: ObjectNode = current
|
||||
parent.set<JsonNode>(
|
||||
paths[paths.size - 1],
|
||||
objectMapper.valueToTree(newValue)
|
||||
)
|
||||
}
|
||||
|
||||
objectMapper.writeValueAsString(objectNode)
|
||||
}
|
||||
json
|
||||
} catch (e: IOException) {
|
||||
throw JsonException("Failed to update node value", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在不同对象类型之间进行转换
|
||||
*
|
||||
* @param source 源对象
|
||||
* @param destinationClass 目标对象类型
|
||||
* @param <T> 源对象类型
|
||||
* @param <D> 目标对象类型
|
||||
* @return 转换后的对象
|
||||
*/
|
||||
override fun <T, D> convert(source: T, destinationClass: Class<D>): D {
|
||||
return objectMapper.convertValue(source, destinationClass)
|
||||
}
|
||||
|
||||
/**
|
||||
* 在不同泛型对象类型之间进行转换
|
||||
*
|
||||
* @param source 源对象
|
||||
* @param destinationType 目标对象的泛型类型引用
|
||||
* @param <T> 源对象类型
|
||||
* @param <D> 目标对象类型
|
||||
* @return 转换后的对象
|
||||
*/
|
||||
override fun <T, D> convert(source: T, destinationType: JsonTypeReference<D>): D {
|
||||
return objectMapper.convertValue(
|
||||
source,
|
||||
objectMapper.constructType(destinationType.type)
|
||||
)
|
||||
}
|
||||
|
||||
override fun addJsonConverter(c: JsonConverter<*, *>) {
|
||||
c.getStringConverter()?.let {
|
||||
objectMapper.registerModule(it.jacksonJsonStringConverterAdapter.jacksonModule)
|
||||
}
|
||||
}
|
||||
|
||||
override fun addJsonStringConverter(c: JsonStringConverter<*>) {
|
||||
addJsonConverter(c)
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile JsonApi.kt
|
||||
* LastUpdate 2025-09-15 11:10:59
|
||||
* LastUpdate 2025-09-15 22:32:50
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -306,8 +306,8 @@ interface JsonApi {
|
||||
* @param <T> 泛型参数,表示List中元素的类型
|
||||
* @return 解析后的List集合
|
||||
</T> */
|
||||
fun <T> parseList(json: String, elementType: Class<T>): MutableList<T> {
|
||||
return parse<MutableList<T>>(json, JsonTypeUtils.listType<T>(elementType))
|
||||
fun <T> parseList(json: String, elementType: Class<T>): List<T> {
|
||||
return parse(json, type = listType(elementType))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -372,7 +372,7 @@ interface JsonApi {
|
||||
* @param path 节点路径(如:"user.name")
|
||||
* @return 节点值的字符串表示
|
||||
*/
|
||||
fun getNodeValue(json: String, path: String): String
|
||||
fun getNodeValue(json: String, path: String): String?
|
||||
|
||||
/**
|
||||
* 更新JSON字符串中指定路径节点的值
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2025 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 JsonException.kt
|
||||
* LastUpdate 2025-09-15 22:32:50
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.json
|
||||
|
||||
class JsonException : RuntimeException {
|
||||
|
||||
constructor(message: String) : super(message)
|
||||
|
||||
constructor(message: String, cause: Throwable) : super(message, cause)
|
||||
|
||||
constructor(cause: Throwable) : this(cause.message ?: "", cause)
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* Copyright 2025 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 JsonTypeReference.kt
|
||||
* LastUpdate 2025-09-15 22:32:50
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.json
|
||||
|
||||
import java.lang.reflect.ParameterizedType
|
||||
import java.lang.reflect.Type
|
||||
import java.util.*
|
||||
|
||||
/**
|
||||
* 通用的 JSON 类型引用类,用于在运行时保留泛型类型信息
|
||||
* 适用于所有 JSON 库(Jackson、Gson、Fastjson 等)
|
||||
*
|
||||
* @param <T> 引用的泛型类型
|
||||
*/
|
||||
abstract class JsonTypeReference<T> : Comparable<JsonTypeReference<T>> {
|
||||
|
||||
open var type: Type = Any::class.java
|
||||
|
||||
/**
|
||||
* 构造函数,通过反射获取泛型类型信息
|
||||
* 仅供内部匿名子类使用
|
||||
*/
|
||||
protected constructor() {
|
||||
val superClass: Type = this.javaClass.genericSuperclass
|
||||
|
||||
// 检查是否为匿名子类,防止直接实例化导致无法获取泛型信息
|
||||
if (superClass is Class<*>) {
|
||||
throw IllegalArgumentException(
|
||||
"必须使用匿名子类方式创建 JsonTypeReference," +
|
||||
"例如: new JsonTypeReference<List<String>>() {}"
|
||||
)
|
||||
}
|
||||
|
||||
this.type = (superClass as ParameterizedType).actualTypeArguments[0]
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数,直接指定类型
|
||||
* @param type 具体的类型信息
|
||||
*/
|
||||
protected constructor(type: Type) {
|
||||
this.type = Objects.requireNonNull(type, "Type cannot be null")
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建类型引用实例
|
||||
* @param <T> 目标类型
|
||||
* @return 类型引用实例
|
||||
*/
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun <T> of(): JsonTypeReference<T> {
|
||||
return object : JsonTypeReference<T>() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 Class 创建类型引用
|
||||
* @param clazz 目标类
|
||||
* @param <T> 目标类型
|
||||
* @return 类型引用实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> of(clazz: Class<T>): JsonTypeReference<T> {
|
||||
return object : JsonTypeReference<T>(clazz) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 Type 创建类型引用
|
||||
* @param type 目标类型
|
||||
* @param <T> 目标类型
|
||||
* @return 类型引用实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> of(type: Type): JsonTypeReference<T> {
|
||||
return object : JsonTypeReference<T>(type) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取原始类型(去掉泛型参数的类型)
|
||||
* @return 原始类型 Class
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun getRawType(): Class<T> {
|
||||
var rawType: Type = type
|
||||
|
||||
// 如果是参数化类型,则提取原始类型部分
|
||||
if (type is ParameterizedType) {
|
||||
rawType = (type as ParameterizedType).rawType
|
||||
}
|
||||
|
||||
if (rawType is Class<*>) {
|
||||
return rawType as Class<T>
|
||||
}
|
||||
|
||||
throw IllegalStateException("无法获取原始类型: $type")
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (other == null || this.javaClass != other.javaClass) return false
|
||||
val that = other as JsonTypeReference<*>
|
||||
|
||||
// 对于 ParameterizedType,需要更完整的比较
|
||||
if (this.type is ParameterizedType && that.type is ParameterizedType) {
|
||||
val thisParamType = this.type as ParameterizedType
|
||||
val thatParamType = that.type as ParameterizedType
|
||||
|
||||
return (
|
||||
Objects.equals(
|
||||
thisParamType.rawType,
|
||||
thatParamType.rawType
|
||||
) &&
|
||||
thisParamType.actualTypeArguments.contentEquals(thatParamType.actualTypeArguments) &&
|
||||
Objects.equals(
|
||||
thisParamType.ownerType,
|
||||
thatParamType.ownerType
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return Objects.equals(type, that.type)
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
if (type is ParameterizedType) {
|
||||
val paramType = type as ParameterizedType
|
||||
return Objects.hash(
|
||||
paramType.rawType,
|
||||
paramType.actualTypeArguments.contentHashCode(),
|
||||
paramType.ownerType
|
||||
)
|
||||
}
|
||||
return Objects.hash(type)
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return "JsonTypeReference{$type}"
|
||||
}
|
||||
|
||||
override fun compareTo(other: JsonTypeReference<T>): Int {
|
||||
return this.type.toString().compareTo(other.type.toString())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
/*
|
||||
* Copyright 2025 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 JsonTypeUtils.kt
|
||||
* LastUpdate 2025-09-15 22:04:54
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
@file:JvmName("JsonTypeUtils")
|
||||
|
||||
package com.mingliqiye.utils.json
|
||||
|
||||
import java.lang.reflect.ParameterizedType
|
||||
import java.lang.reflect.Type
|
||||
import java.util.*
|
||||
|
||||
|
||||
/**
|
||||
* 检查给定的类型是否是指定类或其子类/实现类。
|
||||
*
|
||||
* @param type 要检查的类型
|
||||
* @param expectedClass 期望匹配的类
|
||||
* @return 如果类型匹配则返回 true,否则返回 false
|
||||
*/
|
||||
fun isTypeOf(type: Type, expectedClass: Class<*>): Boolean {
|
||||
return when (type) {
|
||||
is Class<*> -> expectedClass.isAssignableFrom(type)
|
||||
is ParameterizedType -> isTypeOf(type.rawType, expectedClass)
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取泛型类型的参数类型。
|
||||
*
|
||||
* @param type 泛型类型
|
||||
* @param index 参数索引(从0开始)
|
||||
* @return 指定位置的泛型参数类型
|
||||
* @throws IllegalArgumentException 当无法获取指定索引的泛型参数时抛出异常
|
||||
*/
|
||||
fun getGenericParameter(type: Type, index: Int): Type {
|
||||
if (type is ParameterizedType) {
|
||||
val typeArgs = type.actualTypeArguments
|
||||
if (index >= 0 && index < typeArgs.size) {
|
||||
return typeArgs[index]
|
||||
}
|
||||
}
|
||||
throw IllegalArgumentException(
|
||||
"无法获取泛型参数: $type at index $index"
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取类型名称,支持普通类和泛型类型。
|
||||
*
|
||||
* @param type 类型对象
|
||||
* @return 类型名称字符串
|
||||
*/
|
||||
fun getTypeName(type: Type): String {
|
||||
return when (type) {
|
||||
is Class<*> -> type.simpleName
|
||||
is ParameterizedType -> {
|
||||
val rawType = type.rawType as Class<*>
|
||||
val typeArgs = type.actualTypeArguments
|
||||
|
||||
val sb = StringBuilder(rawType.simpleName)
|
||||
sb.append("<")
|
||||
for (i in typeArgs.indices) {
|
||||
if (i > 0) sb.append(", ")
|
||||
sb.append(getTypeName(typeArgs[i]))
|
||||
}
|
||||
sb.append(">")
|
||||
sb.toString()
|
||||
}
|
||||
|
||||
else -> type.typeName
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个表示数组类型的引用对象。
|
||||
*
|
||||
* @param componentType 数组元素的类型
|
||||
* @param <T> 元素类型
|
||||
* @return 表示数组类型的 JsonTypeReference 对象
|
||||
*/
|
||||
fun <T> arrayType(componentType: Class<T>): JsonTypeReference<Array<T>> {
|
||||
return object : JsonTypeReference<Array<T>>() {
|
||||
private val arrayType: Type = java.lang.reflect.Array.newInstance(
|
||||
componentType, 0
|
||||
).javaClass
|
||||
|
||||
override var type: Type = Any::class.java
|
||||
get() = object : ParameterizedType {
|
||||
private val actualTypeArguments = arrayOf<Type>(componentType)
|
||||
|
||||
override fun getActualTypeArguments(): Array<Type> {
|
||||
return actualTypeArguments
|
||||
}
|
||||
|
||||
override fun getRawType(): Type {
|
||||
return arrayType
|
||||
}
|
||||
|
||||
override fun getOwnerType(): Type? {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个表示 List 类型的引用对象。
|
||||
*
|
||||
* @param componentType List 中元素的类型
|
||||
* @param <T> 元素类型
|
||||
* @return 表示 List 类型的 JsonTypeReference 对象
|
||||
* @throws IllegalArgumentException 如果 componentType 为 null,则抛出异常
|
||||
*/
|
||||
fun <T> listType(componentType: Class<T>): JsonTypeReference<List<T>> {
|
||||
|
||||
return object : JsonTypeReference<List<T>>() {
|
||||
override var type: Type = Any::class.java
|
||||
get() = object : ParameterizedType {
|
||||
override fun getActualTypeArguments(): Array<Type> {
|
||||
return arrayOf(componentType)
|
||||
}
|
||||
|
||||
override fun getRawType(): Type {
|
||||
return List::class.java
|
||||
}
|
||||
|
||||
override fun getOwnerType(): Type? {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个表示 Map 类型的引用对象。
|
||||
*
|
||||
* @param keyType Map 键的类型
|
||||
* @param valueType Map 值的类型
|
||||
* @param <K> 键类型
|
||||
* @param <V> 值类型
|
||||
* @return 表示 Map 类型的 JsonTypeReference 对象
|
||||
* @throws IllegalArgumentException 如果 keyType 或 valueType 为 null,则抛出异常
|
||||
*/
|
||||
fun <K, V> MapType(keyType: Class<K>, valueType: Class<V>): JsonTypeReference<Map<K, V>> {
|
||||
|
||||
return object : JsonTypeReference<Map<K, V>>() {
|
||||
override var type: Type = Any::class.java
|
||||
get() = object : ParameterizedType {
|
||||
override fun getActualTypeArguments(): Array<Type> {
|
||||
return arrayOf(keyType, valueType)
|
||||
}
|
||||
|
||||
override fun getRawType(): Type {
|
||||
return Map::class.java
|
||||
}
|
||||
|
||||
override fun getOwnerType(): Type? {
|
||||
return null
|
||||
}
|
||||
|
||||
override fun equals(obj: Any?): Boolean {
|
||||
if (this === obj) return true
|
||||
if (obj !is ParameterizedType) return false
|
||||
|
||||
val that = obj
|
||||
return (Objects.equals(
|
||||
rawType,
|
||||
that.rawType
|
||||
) && actualTypeArguments.contentEquals(that.actualTypeArguments) && Objects.equals(
|
||||
ownerType,
|
||||
that.ownerType
|
||||
))
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
return (actualTypeArguments.contentHashCode() xor Objects.hashCode(rawType) xor Objects.hashCode(
|
||||
ownerType
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user