Search code examples
javaosgiosgi-bundleosgi-fragment

How to set final static variable values in a component by reading the values from fragment?


I am just beginner in OSGi and we are still using version 4. I have a OSGi component where one of the class has public static final (psf) variables.

What I would like to do, I want to use a fragment where it reads the values from properties file and set the values of the psf variables in the component. ? If the fragment is not found, values should be set to default.

Please find my snapshot code and let me know how can i do this ?

Component class

public final class OdsPrincipals {
   /*****************************************************************************************
    * Static/Inner class members
    ******************************************************************************************/

   private static final String ODS_PRODUCT_NAME;
   private static final String ODS_PRINCIPAL_NAME;

   static {
         //How to set the values of static final variables.
   }
   

fragment class

public class OdsPrincipalProperties {

   /*'***************************************************************************************
   *   Static/Inner class members                                         
   ******************************************************************************************/

   protected static final String ODS_PRINCIPAL_PROPERTIES_FILE = "odsprincipal.properties";

   private static final Properties properties = new Properties();

   static {
      try {
         properties.load(
               OdsPrincipalProperties.class.getResourceAsStream(ODS_PRINCIPAL_PROPERTIES_FILE));
      } catch (Exception e) {
         ServiceLogger.error(e);
      } finally {
      }
   }

   private static final OdsPrincipalProperties odsPrincipalProperties = new OdsPrincipalProperties();

   public static OdsPrincipalProperties getInstance() {
      return odsPrincipalProperties;
   }

   /*'***************************************************************************************
   *   Class members                                         
   ******************************************************************************************/

   protected OdsPrincipalProperties() {
   }

   /*
    * returns the value for a given key. If the key is not 
    * found, returns the default value.
    * 
    */

   public String getValue(String key, String defaultValue) {
      return properties.getProperty(key, defaultValue);
   }

} 

Solution

  • You want to set so called compile time constants at runtime. That is by definition not possible. The reason is that at compile time every occurrence of the variable in your code is replaced with the value of the constant. So even if you could change them at runtime the rest of your compiled code would not be updated.