简体   繁体   English

Java setProperty()在运行时不起作用

[英]Java setProperty() is not working in Runtime

I want to implement a Preferences migration from default (Windows HKCU) to my own (filesystem). 我想实现从默认(Windows HKCU)到我自己的(文件系统)的首选项迁移。 Everything is working apart but doesn't work together: 一切都在工作,但不能一起工作:

public static void main(String[] args){

try {

    for(String s : Preferences.systemNodeForPackage(MyPreferences.class).node(myNode).keys()){
        sysHashMap.put(s, Preferences.systemNodeForPackage(MyPreferences.class).node(myNode).get(s, null));
        logger.info("moving key " + s + " from system");
    }
} catch (BackingStoreException ex) {
    java.util.logging.Logger.getLogger(PreferenceManager.class.getName()).log(Level.SEVERE, null, ex);
}

//then I want to switch to my own implemented preferences 
System.setProperty("java.util.prefs.PreferencesFactory", FilePreferencesFactory.class.getName());
//here if I print System.getProperty - I see that property is set to what I want
AppPreferences myNewPreferences = new Preferences();
myNewPreferences.addEntry("key1", "value1");//sets the value to the registry - i.e. old implementation
}


}

If I coment out the "for" loop - everything works as expected, the key-value is written to the file, specified in FilePreferencesFactory. 如果我注释掉“ for”循环-一切都按预期工作,则将键值写入FilePreferencesFactory中指定的文件中。 Why I cannot switch the Preferences Implementation on-the-fly ? 为什么我不能即时切换首选项实现? Is it possible? 可能吗? How can I fix my code? 如何修复我的代码? Thanks in advance. 提前致谢。 Any question will be answered. 任何问题都将得到解答。

An old question, but for anyone interested: 一个古老的问题,但对于任何有兴趣的人:

Your custom preferences factory is only used when you set the system property java.util.prefs.PreferencesFactory before calling systemRoot() or userRoot() (or, in your case executing them indirectly via systemNodeForPackage() ) . 只有在调用systemRoot()userRoot()之前设置系统属性java.util.prefs.PreferencesFactory (或者,通过systemNodeForPackage()间接执行它们systemRoot()之前,才使用自定义首选项工厂。

Otherwise the factory class to be used is already set to a default value and it can only be set once. 否则,要使用的工厂类已经设置为默认值,并且只能设置一次。

(See the initialisation code for the factory in the java.util.prefs.Preferences class). (请参阅java.util.prefs.Preferences类中的工厂初始化代码)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM