美文网首页
kotlin 属性代理 读取Properties 中的属性

kotlin 属性代理 读取Properties 中的属性

作者: 菜鸟何时起飞 | 来源:发表于2020-08-26 11:57 被阅读0次
    class PropertiesDelegate(val path: String) {
    
        val properties: Properties by lazy {
            val prop = Properties()
            try {
                javaClass.getResourceAsStream(path).use {
                    prop.load(it)
                }
            } catch (e: Exception) {
                //logger.error(e.message, e)
                try {
                    ClassLoader.getSystemClassLoader().getResourceAsStream(path).use {
                        prop.load(it)
                    }
                } catch (e: Exception) {
                    //logger.error(e.message, e)
                    FileInputStream(path).use {
                        prop.load(it)
                    }
                }
            }
    
            prop
        }
    
        operator fun <T> getValue(thisRef: Any, property: KProperty<*>): T {
            val value = properties[property.name]
            val classOfT = property.returnType.classifier as KClass<*>
            return if (Number::class.isSuperclassOf(classOfT)) {
                classOfT.javaObjectType.getDeclaredMethod("parse${classOfT.simpleName}", String::class.java).invoke(null, value)
            } else {
                value
            } as T
        }
    
        operator fun <T> setValue(thisRef: Any, property: KProperty<*>, value: T) {
            properties[property.name] = value
            File(path).outputStream().use {
                properties.store(it, "")
            }
        }
    }
    
    abstract class AbsProperties(path: String) {
        protected val prop = PropertiesDelegate(path)
    }
    

    相关文章

      网友评论

          本文标题:kotlin 属性代理 读取Properties 中的属性

          本文链接:https://www.haomeiwen.com/subject/igpxsktx.html