2

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

merlachandra
  • 376
  • 2
  • 17

1 Answers1

3

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).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks Jon Skeet. As I'm Java begginer, I dont know about the reflections feature. I'll go thro it and try that... – merlachandra May 24 '12 at 10:16
  • 1
    @merlachandra: If you're a beginner, I'd suggest staying well away from reflection for the moment. Do things the laborious but straightforward way for the moment. – Jon Skeet May 24 '12 at 10:17
  • Thanks for your suggestion, Currently I'm continuing with the getProperty() for getting individual properties to my program. – merlachandra May 24 '12 at 10:35