From a478b85ba2f71b7b2cd67b5ece1aeba209db6ef2 Mon Sep 17 00:00:00 2001 From: Him188 Date: Thu, 20 Aug 2020 12:52:19 +0800 Subject: [PATCH] Add ClassLoader.asResourceContainer; Fix nullability of getResource --- .../mirai/console/util/ResourceContainer.kt | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/backend/mirai-console/src/main/kotlin/net/mamoe/mirai/console/util/ResourceContainer.kt b/backend/mirai-console/src/main/kotlin/net/mamoe/mirai/console/util/ResourceContainer.kt index 891bc36e4..2d6952ce2 100644 --- a/backend/mirai-console/src/main/kotlin/net/mamoe/mirai/console/util/ResourceContainer.kt +++ b/backend/mirai-console/src/main/kotlin/net/mamoe/mirai/console/util/ResourceContainer.kt @@ -22,26 +22,26 @@ import kotlin.reflect.KClass * * 资源容器可能使用 [Class.getResourceAsStream], 也可能使用其他方式, 取决于实现方式. * - * @see JvmPlugin [JvmPlugin] 实现 [ResourceContainer], 使用 [ResourceContainer.asResourceContainer] + * @see JvmPlugin [JvmPlugin] 通过 [ClassLoader.getResourceAsStream] 实现 [ResourceContainer], 使用 [ResourceContainer.asResourceContainer] */ public interface ResourceContainer { /** * 获取一个资源文件 */ - public fun getResourceAsStream(name: String): InputStream + public fun getResourceAsStream(name: String): InputStream? /** * 读取一个资源文件并以 [Charsets.UTF_8] 编码为 [String] */ @JvmDefault - public fun getResource(name: String): String = getResource(name, Charsets.UTF_8) + public fun getResource(name: String): String? = getResource(name, Charsets.UTF_8) /** * 读取一个资源文件并以 [charset] 编码为 [String] */ @JvmDefault - public fun getResource(name: String, charset: Charset): String = - String(this.getResourceAsStream(name).use { it.readBytes() }) + public fun getResource(name: String, charset: Charset): String? = + this.getResourceAsStream(name)?.use(InputStream::readBytes)?.let(::String) public companion object { /** @@ -51,6 +51,13 @@ public interface ResourceContainer { @JvmName("create") public fun KClass<*>.asResourceContainer(): ResourceContainer = this.java.asResourceContainer() + /** + * 使用 [Class.getResourceAsStream] 读取资源文件 + */ + @JvmStatic + @JvmName("create") + public fun ClassLoader.asResourceContainer(): ResourceContainer = ClassLoaderAsResourceContainer(this) + /** * 使用 [Class.getResourceAsStream] 读取资源文件 */ @@ -63,5 +70,11 @@ public interface ResourceContainer { private class ClassAsResourceContainer( private val clazz: Class<*> ) : ResourceContainer { - override fun getResourceAsStream(name: String): InputStream = clazz.getResourceAsStream(name) + override fun getResourceAsStream(name: String): InputStream? = clazz.getResourceAsStream(name) +} + +private class ClassLoaderAsResourceContainer( + private val clazz: ClassLoader +) : ResourceContainer { + override fun getResourceAsStream(name: String): InputStream? = clazz.getResourceAsStream(name) } \ No newline at end of file