This commit is contained in:
2026-10-20 20:05:40 +08:00
parent 474071e43b
commit 31987b9b14
9 changed files with 1618 additions and 536 deletions
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile NettyUtils.kt
* LastUpdate 2026-06-27 21:40:00
* LastUpdate 2026-10-20 20:05:37
* UpdateUser MingLiPro
*/
@@ -323,7 +323,7 @@ fun ByteBuf.releaseSafely(): Boolean {
*/
fun ByteBuf.tryRelease(): Boolean {
return try {
if (refCnt() > 0) release() else false
refCnt() > 0 && release()
} catch (e: Exception) {
false
}
@@ -1,5 +1,5 @@
/*
* Copyright 2025 mingliqiye
* 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.
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile OsPath.kt
* LastUpdate 2025-09-18 09:47:43
* LastUpdate 2026-10-20 20:05:37
* UpdateUser MingLiPro
*/
@@ -26,8 +26,7 @@ package com.mingliqiye.utils.path
import java.io.File
import java.net.URI
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.*
import java.util.*
import java.util.function.Consumer
@@ -40,6 +39,41 @@ class OsPath private constructor(private val path: Path) : Path by path {
return path.spliterator()
}
override fun startsWith(other: String): Boolean {
return path.startsWith(other)
}
override fun endsWith(other: String): Boolean {
return path.endsWith(other)
}
override fun resolve(other: String): Path {
return path.resolve(other)
}
override fun resolveSibling(other: Path): Path {
return path.resolveSibling(other)
}
override fun resolveSibling(other: String): Path {
return path.resolveSibling(other)
}
override fun toFile(): File {
return path.toFile()
}
override fun register(
watcher: WatchService,
vararg events: WatchEvent.Kind<*>,
): WatchKey {
return path.register(watcher, *events)
}
override fun iterator(): MutableIterator<Path> {
return path.iterator()
}
companion object {
@JvmStatic
fun of(path: String): OsPath {
@@ -15,10 +15,11 @@
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile RandomBytes.kt
* LastUpdate 2026-10-11 17:11:11
* CurrentFile Random.kt
* LastUpdate 2026-10-20 20:05:37
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.random
import java.security.SecureRandom
@@ -44,7 +45,7 @@ object Random {
* 通过lazy委托延迟初始化
*/
private val random: Random by lazy {
Random
Random.Default
}
/**
@@ -1,229 +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 Require.kt
* LastUpdate 2026-02-24 09:03:42
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.require
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.slf4j.Logger
import java.lang.reflect.Constructor
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlin.reflect.KClass
/**
* 条件检查工具对象,提供多种重载的require方法用于参数验证和异常抛出
* 支持自定义异常类型、延迟消息构造和日志记录功能
*/
object Require {
@JvmStatic
var logger: Logger? = MingLiLoggerFactory.getLogger<Require>()
@JvmStatic
var isLogError = true
/**
* 检查条件是否满足,如果不满足则抛出指定类型的异常
* @param value 要检查的布尔条件
* @param throwable 异常类型Class对象
* @param layzMessage 延迟消息构造器
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, throwable: Class<out Throwable>, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
require(value, layzMessage.call(), throwable)
}
/**
* 检查条件是否满足,如果不满足则抛出指定类型的异常
* @param value 要检查的布尔条件
* @param throwable 异常类型KClass对象
* @param layzMessage 延迟消息构造器
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, throwable: KClass<out Throwable>, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
require(value, throwable.java, layzMessage)
}
/**
* 检查条件是否满足,如果不满足则抛出延迟构造的异常
* @param value 要检查的布尔条件
* @param layzThrowable 延迟异常构造器
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, layzThrowable: RequireLayzExceptionConstructor) {
contract {
returns() implies value
}
if (!value) throwThrowable(layzThrowable.call())
}
/**
* 检查条件是否满足,如果不满足则抛出指定消息和类型的异常
* @param value 要检查的布尔条件
* @param message 异常消息
* @param throwable 异常类型Class对象
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, message: String, throwable: Class<out Throwable>) {
contract {
returns() implies value
}
if (!value) throwThrowable(getExceptionConstructor(throwable).newInstance(message))
}
/**
* 检查条件是否满足,如果不满足则抛出指定消息和类型的异常
* @param value 要检查的布尔条件
* @param message 异常消息
* @param throwable 异常类型KClass对象
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, message: String, throwable: KClass<out Throwable>) {
contract {
returns() implies value
}
require(value, message, throwable.java)
}
/**
* 抛出异常并在启用日志时记录错误信息
* @param throwable 要抛出的异常对象
*/
@JvmStatic
fun throwThrowable(throwable: Throwable) {
if (isLogError && logger != null) logger!!.error(throwable.message, throwable)
throw throwable
}
/**
* 内联函数版本的条件检查,支持泛型异常类型
* @param T 异常类型
* @param value 要检查的布尔条件
* @param message 异常消息
*/
@OptIn(ExperimentalContracts::class)
@JvmName("__inline_Require")
@JvmStatic
inline fun <reified T : Throwable> require(value: Boolean, message: String) {
contract {
returns() implies value
}
require(value, message, T::class.java)
}
/**
* 内联函数版本的条件检查,支持泛型异常类型和延迟消息构造
* @param T 异常类型
* @param value 要检查的布尔条件
* @param layzMessage 延迟消息构造器
*/
@OptIn(ExperimentalContracts::class)
@JvmName("__inline_Require")
@JvmStatic
inline fun <reified T : Throwable> require(value: Boolean, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
if (!value) throwThrowable(getExceptionConstructor<T>().newInstance(layzMessage.call()))
}
/**
* 获取指定异常类型的构造函数(内联泛型版本)
* @param T 异常类型
* @return 异常类型的构造函数
*/
@JvmName("__inline_GetExceptionConstructor")
@JvmStatic
inline fun <reified T : Throwable> getExceptionConstructor(): Constructor<out T> =
getExceptionConstructor(T::class.java)
/**
* 获取指定异常类型的构造函数
* @param throwable 异常类型Class对象
* @return 异常类型的构造函数
*/
@JvmStatic
@JvmName("__GetExceptionConstructor")
fun <T : Throwable> getExceptionConstructor(throwable: Class<out T>): Constructor<out T> =
throwable.getConstructor(String::class.java)
/**
* 获取指定异常类型的构造函数
* @param throwable 异常类型KClass对象
* @return 异常类型的构造函数
*/
@JvmStatic
@JvmName("__GetExceptionConstructor")
fun <T : Throwable> getExceptionConstructor(throwable: KClass<out T>): Constructor<out T> =
getExceptionConstructor(throwable.java)
/**
* 基础条件检查方法,不满足条件时抛出IllegalArgumentException
* @param value 要检查的布尔条件
*/
@OptIn(ExperimentalContracts::class)
@JvmStatic
fun require(value: Boolean) {
contract {
returns() implies value
}
require(value, "the require conditions are not met.")
}
/**
* 使用延迟消息构造器进行条件检查,不满足时抛出IllegalArgumentException
* @param value 要检查的布尔条件
* @param layzMessage 延迟消息构造器
*/
@OptIn(ExperimentalContracts::class)
@JvmStatic
fun requireLayzMessage(value: Boolean, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
require(value, IllegalArgumentException::class.java, layzMessage)
}
/**
* 带消息的条件检查方法,不满足条件时抛出IllegalArgumentException
* @param value 要检查的布尔条件
* @param message 异常消息
*/
@OptIn(ExperimentalContracts::class)
@JvmStatic
fun require(value: Boolean, message: String) {
contract {
returns() implies value
}
if (!value) throwThrowable(getExceptionConstructor(IllegalArgumentException::class.java).newInstance(message))
}
}
@@ -0,0 +1,190 @@
/*
* 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 RequireTrue.kt
* LastUpdate 2026-10-20 20:05:24
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.require
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
const val DEFAULT_MESSAGE = "required fail"
class Required<T : Throwable>(private val newException: (message: String) -> T) {
@OptIn(ExperimentalContracts::class)
fun requireTrue(value: Boolean, message: String) {
contract {
returns() implies value
}
requireTrue(value) { message }
}
@OptIn(ExperimentalContracts::class)
fun requireTrue(value: Boolean) {
contract {
returns() implies value
}
requireTrue(value) { DEFAULT_MESSAGE }
}
@OptIn(ExperimentalContracts::class)
fun requireTrue(value: Boolean, lazyMessage: () -> String) {
contract {
returns() implies value
}
if (!value) {
throw newException(lazyMessage())
}
}
}
fun newRequired(): Required<IllegalArgumentException> {
return newRequired<IllegalArgumentException>()
}
fun <T : Throwable> newRequired(clazz: Class<T>): Required<T> {
return Required {
newException(clazz, it)
}
}
inline fun <reified T : Throwable> newRequired(): Required<T> {
return newRequired(T::class.java)
}
fun <T : Throwable> newException(clazz: Class<T>, msg: String): T = try {
val constructor = clazz.getConstructor(String::class.java).also {
check(!java.lang.reflect.Modifier.isAbstract(clazz.modifiers)) {
"${clazz.name} 是抽象类,无法实例化"
}
}
constructor.newInstance(msg)
} catch (e: ReflectiveOperationException) {
throw IllegalStateException("无法实例化 ${clazz.name}", e)
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> requireTrue(value: Boolean, clazz: Class<T>, lazyMessage: () -> String) {
contract {
returns() implies value
}
if (!value) {
throw newException(clazz, lazyMessage())
}
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> requireTrue(value: Boolean, noinline lazyMessage: () -> String) {
contract {
returns() implies value
}
requireTrue(value, T::class.java, lazyMessage)
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> Boolean.requireTrue(clazz: Class<T>, lazyMessage: () -> String) {
contract {
returns() implies this@requireTrue
}
requireTrue(this, clazz, lazyMessage)
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> Boolean.requireTrue(clazz: Class<T>, message: String) {
contract {
returns() implies this@requireTrue
}
requireTrue(this, clazz) {
message
}
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> requireTrue(value: Boolean, clazz: Class<T>, message: String) {
contract {
returns() implies value
}
requireTrue(value, clazz) { message }
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> requireTrue(value: Boolean, message: String) {
contract {
returns() implies value
}
requireTrue(value, T::class.java) { message }
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> Boolean.requireTrue(noinline lazyMessage: () -> String) {
contract {
returns() implies this@requireTrue
}
requireTrue(this, T::class.java, lazyMessage)
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> Boolean.requireTrue(message: String) {
contract {
returns() implies this@requireTrue
}
requireTrue(this, T::class.java, message)
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> requireTrue(value: Boolean, clazz: Class<T>) {
contract {
returns() implies value
}
requireTrue(value, clazz) { DEFAULT_MESSAGE }
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> requireTrue(value: Boolean) {
contract {
returns() implies value
}
requireTrue(value, T::class.java) { DEFAULT_MESSAGE }
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> Boolean.requireTrue(clazz: Class<T>) {
contract {
returns() implies this@requireTrue
}
requireTrue(this, clazz) { DEFAULT_MESSAGE }
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> Boolean.requireTrue() {
contract {
returns() implies this@requireTrue
}
requireTrue(this, T::class.java) { DEFAULT_MESSAGE }
}
@@ -0,0 +1,23 @@
/*
* 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 Required.kt
* LastUpdate 2026-10-20 19:58:06
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.require
File diff suppressed because it is too large Load Diff
@@ -16,444 +16,271 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile SystemUtil.kt
* LastUpdate 2026-03-27 09:35:40
* LastUpdate 2026-10-20 18:54:24
* UpdateUser MingLiPro
*/
@file:JvmName("SystemUtils")
package com.mingliqiye.utils.system
import java.lang.management.ManagementFactory
import java.net.*
import java.util.*
import com.mingliqiye.utils.random.Random.nextBytes as randomByte
private val UNIX_PREFIXES = arrayOf("Linux", "AIX", "SunOS", "Mac OS X", "FreeBSD")
private val HEX_UPPER: Array<String> = Array(256) { "%02X".format(it) }
private fun <T> Enumeration<T>?.toList(): List<T> =
if (this == null) emptyList() else Collections.list(this)
/**
* 操作系统名称属性,延迟初始化
*/
val osName: String? by lazy {
System.getProperties().getProperty("os.name")
runCatching { System.getProperty("os.name") }.getOrNull()
}
/**
* 判断当前操作系统是否为Windows系统
*
* @return 如果是Windows系统返回true,否则返回false
* 判断当前操作系统是否为 Windows
*/
val isWindows: Boolean by lazy {
osName != null && osName!!.startsWith("Windows")
osName?.startsWith("Windows") == true
}
/**
* 判断当前操作系统是否为Mac系统
*
* @return 如果是Mac系统返回true,否则返回false
* 判断当前操作系统是否为 Mac
*/
val isMac: Boolean by lazy {
osName != null && osName!!.startsWith("Mac")
osName?.startsWith("Mac") == true
}
/**
* 判断当前操作系统是否为Unix/Linux系统
*
* @return 如果是Unix/Linux系统返回true,否则返回false
* 判断当前操作系统是否为 Unix/Linux(含 macOS)
*/
val isUnix: Boolean by lazy {
if (osName == null) {
false
} else {
(osName!!.startsWith("Linux") || osName!!.startsWith("AIX") || osName!!.startsWith("SunOS") || osName!!.startsWith(
"Mac OS X"
) || osName!!.startsWith(
"FreeBSD"
))
}
val name = osName ?: return@lazy false
UNIX_PREFIXES.any { name.startsWith(it) }
}
/**
* JDK版本号属性,延迟初始化
* JDK 版本号属性,延迟初始化
*/
val jdkVersion: String? by lazy {
System.getProperty("java.specification.version")
runCatching { System.getProperty("java.specification.version") }.getOrNull()
}
/**
* Java版本号的整数形式属性,延迟初始化
* Java 版本号的主版本整数,延迟初始化
*
* 同时兼容 `1.8` 旧式版本号与 `9` / `17` / `100` 等新式版本号。
*
* @throws IllegalStateException 无法解析出整数版本时抛出
*/
val javaVersionAsInteger: Int by lazy {
val version = jdkVersion
if (version == null || version.isEmpty()) {
if (version.isNullOrBlank()) {
throw IllegalStateException(
"Unable to determine Java version from property 'java.specification.version'"
)
}
val uversion: String = if (version.startsWith("1.")) {
if (version.length < 3) {
throw IllegalStateException(
"Invalid Java version format: $version"
)
}
version[2] + ""
} else {
if (version.length < 2) {
throw IllegalStateException(
"Invalid Java version format: $version"
)
}
version.take(2)
}
uversion.toInt()
val normalized = if (version.startsWith("1.")) version.substring(2) else version
val major = normalized.substringBefore('.').substringBefore('-')
major.toIntOrNull()
?: throw IllegalStateException("Invalid Java version format: $version")
}
/**
* 判断当前JDK版本是否大于8
*
* @return 如果JDK版本大于8返回true,否则返回false
* 判断当前 JDK 版本是否大于 8
*/
val isJdk8Plus: Boolean by lazy {
javaVersionAsInteger > 8
}
/**
* 本地IP地址数组,延迟初始化
* 本地 IPv4 地址数组,跳过回环、虚拟与未启用网卡
*
* @throws RuntimeException 当获取网络接口信息失败时抛出
* @throws RuntimeException 网络接口枚举失败时抛出
*/
val localIps: Array<String> by lazy {
try {
val ipList: MutableList<String> = ArrayList()
val interfaces = NetworkInterface.getNetworkInterfaces()
while (interfaces.hasMoreElements()) {
val networkInterface = interfaces.nextElement()
// 跳过回环接口和虚拟接口
if (networkInterface.isLoopback || networkInterface.isVirtual || !networkInterface.isUp) {
continue
}
val addresses = networkInterface.inetAddresses
while (addresses.hasMoreElements()) {
val address = addresses.nextElement()
// 只获取IPv4地址
if (address is Inet4Address) {
ipList.add(address.hostAddress)
}
}
}
ipList.toTypedArray()
activeNetworkInterfaces()
.flatMap { it.inetAddresses.toList() }
.filterIsInstance<Inet4Address>()
.mapNotNull { it.hostAddress }
.toList()
.toTypedArray()
} catch (e: SocketException) {
throw RuntimeException("Failed to get local IP addresses", e)
}
}
/**
* 本地IP地址列表,延迟初始化
* 本地 IPv4 地址列表
*/
val localIpsByList: List<String> by lazy {
localIps.toList()
}
val localIpsByList: List<String> by lazy { localIps.toList() }
/**
* 本地回环地址数组,延迟初始化
* 本地回环地址数组;枚举失败时至少包含 `127.0.0.1`
*/
val loopbackIps: Array<String> by lazy {
val strings: MutableList<String> = ArrayList(3)
return@lazy try {
val interfaces = NetworkInterface.getNetworkInterfaces()
while (interfaces.hasMoreElements()) {
val networkInterface = interfaces.nextElement()
// 只处理回环接口
if (networkInterface.isLoopback && networkInterface.isUp) {
val addresses = networkInterface.inetAddresses
while (addresses.hasMoreElements()) {
val address = addresses.nextElement()
strings.add(address.hostAddress)
}
}
}
strings.toTypedArray()
} catch (e: SocketException) {
try {
NetworkInterface.getNetworkInterfaces().toList()
.asSequence()
.filter { it.isLoopback && it.isUp }
.flatMap { it.inetAddresses.toList().asSequence() }
.mapNotNull { it.hostAddress }
.toList()
.toTypedArray()
} catch (_: SocketException) {
arrayOf("127.0.0.1")
}
}
/**
* 本地回环地址IP列表,延迟初始化
* 本地回环地址列表
*/
val loopbackIpsByList: List<String> by lazy {
loopbackIps.toList()
}
val loopbackIpsByList: List<String> by lazy { loopbackIps.toList() }
/**
* 获取当前进程的PID
*
* @return 进程ID,如果无法获取则返回-1
* 当前进程 PID;获取失败返回 -1
*/
val getPid: Long by lazy {
try {
val name = ManagementFactory.getRuntimeMXBean().name
val index = name.indexOf('@')
if (index > 0) {
name.take(index).toLong()
} else {
-1L
}
} catch (e: Exception) {
-1L
}
runCatching { ProcessHandle.current().pid() }.getOrElse { -1L }
}
/**
* 获取当前进程的PID字符串形式
*
* @return 进程ID字符串,如果无法获取则返回"-1"
* 当前进程 PID 字符串;获取失败返回 "-1"
*/
val pidAsString: String by lazy {
try {
val name = ManagementFactory.getRuntimeMXBean().name
val index = name.indexOf('@')
if (index > 0) {
name.take(index)
} else {
"-1"
}
} catch (e: Exception) {
"-1"
}
val pid = getPid
if (pid == -1L) "-1" else pid.toString()
}
/**
* 获取计算机名
*
* @return 计算机名,如果无法获取则返回"unknown"
* 计算机名;获取失败返回 "unknown"
*/
val computerName: String by lazy {
try {
var name = System.getenv("COMPUTERNAME")
if (name.isNullOrBlank()) {
name = System.getenv("HOSTNAME")
}
if (name.isNullOrBlank()) {
name = InetAddress.getLocalHost().hostName
}
name ?: "unknown"
} catch (e: Exception) {
"unknown"
}
getEnvVar("COMPUTERNAME")
?: getEnvVar("HOSTNAME")
?: runCatching { InetAddress.getLocalHost().hostName }.getOrNull()?.takeIf { it.isNotBlank() }
?: "unknown"
}
/**
* 获取当前用户名
*
* @return 当前用户名,如果无法获取则返回"unknown"
* 当前用户名;获取失败返回 "unknown"
*/
val userName: String by lazy {
try {
getEnvVar("USERNAME") ?: getEnvVar("USER") ?: System.getProperty("user.name") ?: "unknown"
} catch (e: SecurityException) {
"unknown"
} catch (e: Exception) {
"unknown"
}
getEnvVar("USERNAME")
?: getEnvVar("USER")
?: runCatching { System.getProperty("user.name") }.getOrNull()?.takeIf { it.isNotBlank() }
?: "unknown"
}
private fun getEnvVar(name: String): String? {
return try {
System.getenv(name)?.takeIf { it.isNotBlank() }
} catch (e: SecurityException) {
null
}
}
private fun getEnvVar(name: String): String? = runCatching {
System.getenv(name)?.takeIf { it.isNotBlank() }
}.getOrNull()
/**
* 获取本机MAC地址的字节数组形式
* 本机 MAC 地址字节数组
*
* @return MAC地址字节数组,如果无法获取则返回空数组
* 未找到可用网卡时回退为 6 字节随机数,避免下游拿到空数组导致错误。
*/
val macAddressBytes: ByteArray by lazy {
try {
val interfaces = NetworkInterface.getNetworkInterfaces()
while (interfaces.hasMoreElements()) {
val networkInterface = interfaces.nextElement()
// 跳过回环接口和虚拟接口
if (networkInterface.isLoopback || networkInterface.isVirtual || !networkInterface.isUp) {
continue
}
val mac = networkInterface.hardwareAddress
if (mac != null && mac.isNotEmpty()) {
return@lazy mac
}
}
randomByte(6)
} catch (e: SocketException) {
randomByte(6)
} catch (e: Exception) {
randomByte(6)
val found = try {
activeNetworkInterfaces()
.mapNotNull { runCatching { it.hardwareAddress }.getOrNull() }
.firstOrNull { it.isNotEmpty() }
} catch (_: SocketException) {
null
}
found ?: randomByte(6)
}
/**
* 获取本机MAC地址的十六进制字符串列表形式
*
* @return MAC地址字符串列表,每个元素表示一个字节的十六进制值(大写),如果无法获取则返回空列表
* 本机 MAC 地址的十六进制字符串列表(大写)
*/
val macAddressStringList: List<String> by lazy {
val macBytes = macAddressBytes
if (macBytes.isEmpty()) {
return@lazy emptyList()
}
macBytes.map { String.format("%02X", it) }
macAddressBytes.map { HEX_UPPER[it.toInt() and 0xFF] }
}
/**
* 获取本机MAC地址的格式化字符串形式(如 "00:11:22:33:44:55")
*
* @return 格式化的MAC地址字符串,如果无法获取则返回空字符串
* 本机 MAC 地址的格式化字符串,如 `00:11:22:33:44:55`
*/
val macAddressFormattedString: String by lazy {
val macBytes = macAddressBytes
if (macBytes.isEmpty()) {
return@lazy ""
}
macBytes.joinToString(":") { String.format("%02X", it) }
macAddressBytes.joinToString(":") { HEX_UPPER[it.toInt() and 0xFF] }
}
/**
* 获取所有网络接口的MAC地址映射
*
* @return Map结构,key为网络接口名称,value为对应的MAC地址字节数组
* 所有非回环、非虚拟网卡的 MAC 地址映射,key 为网卡名
*/
val allMacAddresses: Map<String, ByteArray> by lazy {
try {
val result = mutableMapOf<String, ByteArray>()
val interfaces = NetworkInterface.getNetworkInterfaces()
while (interfaces.hasMoreElements()) {
val networkInterface = interfaces.nextElement()
// 跳过回环接口和虚拟接口
if (networkInterface.isLoopback || networkInterface.isVirtual) {
continue
NetworkInterface.getNetworkInterfaces().toList()
.asSequence()
.filter { !it.isLoopback && !it.isVirtual }
.mapNotNull { ni ->
val mac = runCatching { ni.hardwareAddress }.getOrNull()
if (mac != null && mac.isNotEmpty()) ni.name to mac else null
}
val mac = networkInterface.hardwareAddress
if (mac != null && mac.isNotEmpty()) {
result[networkInterface.name] = mac
}
}
result
} catch (e: SocketException) {
emptyMap()
} catch (e: Exception) {
.toMap()
} catch (_: SocketException) {
emptyMap()
}
}
/**
* 获取所有网络接口的MAC地址字符串列表映射
*
* @return Map结构,key为网络接口名称,value为对应的MAC地址字符串列表
* 所有网卡 MAC 地址的十六进制字符串列表映射
*/
val allMacAddressesStringList: Map<String, List<String>> by lazy {
allMacAddresses.mapValues { entry ->
entry.value.map { String.format("%02X", it) }
}
allMacAddresses.mapValues { (_, bytes) -> bytes.map { HEX_UPPER[it.toInt() and 0xFF] } }
}
/**
* 获取可用处理器数量的懒加载属性
* 可用处理器数量
*/
val availableProcessors: Int by lazy {
Runtime.getRuntime().availableProcessors()
}
private var isLoadprotocol = false
private var protocol = ""
private fun activeNetworkInterfaces(): Sequence<NetworkInterface> =
NetworkInterface.getNetworkInterfaces().toList().asSequence()
.filter { !it.isLoopback && !it.isVirtual && it.isUp }
/**
* 判断是否为开发模式(file协议)
*/
val isDevMode: Boolean by lazy {
protocol == "file"
private val protocol: String by lazy {
val target = ProtocolAnchor::class.java
val resourceName = target.simpleName + ".class"
val resource: URL = target.getResource(resourceName)
?: throw IllegalStateException(
"Unable to locate resource '$resourceName' for class ${target.name}"
)
resource.protocol
}
/**
* 判断是否不为开发模式
*/
val isNotDevMode: Boolean by lazy {
protocol != "file"
}
/**
* 判断是否为JAR模式
*/
val isJarMode: Boolean by lazy {
protocol == "jar"
}
/** 是否为开发模式(file 协议) */
val isDevMode: Boolean get() = protocol == "file"
/**
* 判断是否不为JAR模式
*/
val isNotJarMode: Boolean by lazy {
protocol != "jar"
}
/** 是否不为开发模式 */
val isNotDevMode: Boolean get() = protocol != "file"
/**
* 判断是否为WAR模式
*/
val isWarMode: Boolean by lazy {
protocol == "war"
}
/** 是否为 JAR 模式 */
val isJarMode: Boolean get() = protocol == "jar"
/**
* 判断是否不为WAR模式
*/
val isNotMode: Boolean by lazy {
protocol != "war"
}
/** 是否不为 JAR 模式 */
val isNotJarMode: Boolean get() = protocol != "jar"
/**
* 判断是否为JSWAR模式
*/
val isJswarMode: Boolean by lazy {
protocol == "jswar"
}
/** 是否为 WAR 模式 */
val isWarMode: Boolean get() = protocol == "war"
/**
* 判断是否不为JSWAR模式
*/
val isNotJswarMode: Boolean by lazy {
protocol != "jswar"
}
/** 是否不为 WAR 模式 */
val isNotWarMode: Boolean get() = protocol != "war"
/**
* 加载并获取资源协议
* @param clazz 要获取协议的类对象,默认为null
* @return 返回资源的协议字符串
*/
fun loadProtocol(clazz: Class<*>? = null): String {
// 如果已经加载过协议且clazz为null,则直接返回已缓存的协议
if (isLoadprotocol && clazz == null) {
return protocol
}
val resource: URL? = clazz!!.getResource(
clazz.getSimpleName() + ".class"
)
protocol = resource!!.protocol
return protocol.let {
isLoadprotocol = true
it
}
}
/** 是否为 JSWAR 模式 */
val isJswarMode: Boolean get() = protocol == "jswar"
/** 是否不为 JSWAR 模式 */
val isNotJswarMode: Boolean get() = protocol != "jswar"
private object ProtocolAnchor