Make Java Properties available across classes?

前端 未结 8 2252
情深已故
情深已故 2020-12-30 08:16

I chose to take properties file for customization of some settings. I use the following code to make a Properties Object available in a class

Properties defa         


        
8条回答
  •  误落风尘
    2020-12-30 08:33

    If you only need one instance of your properties class you can use the singleton (anti?)-pattern.

    It would look like a class like this:

    public class MyProperties extends Properties {
        private static MyProperties instance = null;
    
        private MyProperties() {
        }
    
        public static MyProperties getInstance() {
            if (instance == null) {
                try {
                    instance = new MyProperties();
                    FileInputStream in = new FileInputStream("custom.properties");
                    instance.load(in);
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
            return instance;
        }
    }
    

提交回复
热议问题