这就是我的自定义
PersistentStateComponent
子类的样子:
@State(name = "Configurations", storages = [Storage("conf.xml")])
@Service(Service.Level.PROJECT)
class CustomConfigurationService : PersistentStateComponent<CustomConfigurationService> {
var configurations = Configurations()
override fun getState() = this
override fun loadState(service: CustomConfigurationService) {
XmlSerializerUtil.copyBean(service, this)
}
// ...
}
data class Configurations(
val aBoolean: Boolean = false,
val aString: String? = null,
val anotherString: String? = null
)
这就是配置的存储方式(通过 UI 更改后):
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Configurations">
<option name="configurations">
<Configurations />
</option>
</component>
</project>
如果我将超级类型更改为
PersistentStateComponent<Configurations>
,则根本不会创建该文件。
为什么 IntelliJ 不序列化
Configurations
对象的属性?除了将 Configurations
的属性直接放在 CustomConfigurationService
内部之外,我还能做什么?
事实证明我被误导了。最终代码如下所示:
import com.intellij.openapi.components.BaseState
class Configurations : BaseState() {
// property() and string() are BaseState methods
var aBoolean by property(false)
var aString by string(null)
var anotherString by string(null)
}
import com.intellij.openapi.components.SimplePersistentStateComponent
import com.intellij.util.xmlb.XmlSerializerUtil
@State(name = "Configurations", storages = [Storage("conf.xml")])
@Service(Service.Level.PROJECT)
class CustomConfigurationService :
// This takes care of everything else and gives us a .state property
SimplePersistentStateComponent<Configurations>(Configurations()) {
// ...which I shadow using this other property.
override var configurations: Configurations
get() = state
set(value) = XmlSerializerUtil.copyBean(value, state)
companion object {
fun getInstance() = service<ConfigurationService>()
}
}
conf.xml
的内容最终看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Configurations">
<option name="aBoolean" value="true" />
<option name="aString" value="Foobar">
</component>
</project>