How to take all the properties of a property file as initialized variables inside a java program?

StackOverflow https://stackoverflow.com/questions/10733068

  •  10-06-2021
  •  | 
  •  

Question

I'm using properties file in my java program.

Currently whenever I'm need of some property from properties file, I'm using propertyFile.getProperty(propertyKeyName);and taking this into some variable: String propertyName1 = propertyFile.getProperty(propertyKeyName);

Is there any way that with out explicitly defining a variable (propertyName1) and initializing it using getProperty(), Can I get the all the Key=Value of a properties file as String variable which has been initialized "String Key=Value" inside my program?

Thanks, Chandra

Was it helpful?

Solution

No. Variables are declared at compile-time - their names (for instance/static variables, at least) and types are baked into the class file. How could that possibly work when the names are only known at execution time?

What would you expect to happen if wrote an expression which referred to a variable which "didn't exist" at execution time due to the contents of the properties file?

Now what you can do is write a class to initialize an instance of a class via reflection - you could write your class:

public class Person
{
    private String firstName;
    private String lastName;
    private String jobTitle;
    // Whatever... accessors etc
}

and then use reflection to create an instance of Person with values populated from a properties file. That mechanism could then fail at load time if some properties were missing (if you wanted it to).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top