0

i'm looking to declare a constant in the class, so that it'll be set the first thing when the class is loaded, and won't change.

However, the value it should be set to depends on the content of the file the class reads from a file. The following won't work:

static final int N=someMethod(path); 

unless I also have:

static Path path = Paths.get("C:\\Users\\Me\\S2.txt");

If i do this, the param of Paths.get() will have to be manually changed for each run.

Giving the path name on invocation of Java won't do either-- that's solely the String[] argument of the main() method(?), and main() doesn't run till later.

Is there a better way of doing this than what i do in the above two lines of code?

TIA

user3880721
  • 613
  • 6
  • 16
  • Static members are set when the class is loaded. You might be able to play games with a custom `ClassLoader` but therein lies madness. Maybe if you explain why you need this we can suggest a better alternative. Why does it have to be final? You can set it when the value is available and ensure it's immutable. – Jim Garrison Sep 12 '14 at 22:12
  • @JimGarrison can do without that var N be final-- but looks better as a constant. The class will load a problem instance of which the size is N-- read the file and initialize the data strcs all in the static zone. then will explore solution space in non-static instances. don't want N-- the size param be touched once it's set among all these. – user3880721 Sep 12 '14 at 22:14
  • 2
    @user3880721: Reading a file in a static initializer is just a bad idea. Make an *instance*. The instance can be a singleton, but make it an instance so that the code getting that instance can handle the exception caused by trying to read the file and any of the things that can go wrong there. – T.J. Crowder Sep 12 '14 at 22:15
  • @T.J.Crowder i'll have multiple instances. singleton wont fit. that's why i'm going static. agree your first sentence though. – user3880721 Sep 12 '14 at 22:17
  • If multiple instances depend on the same value, you might benefit from using dependency injection. You should try to limit how much you use `static` members, especially when you need dynamic behavior. – Sotirios Delimanolis Sep 12 '14 at 22:18

2 Answers2

1

It doesn't make sense to declare constant value and set it's value to reference to another value in my opinion. I would say that it's better to use system properties in your situation. Answer to this question quite clearly explains how to do this: setting system property

Community
  • 1
  • 1
Lucas
  • 3,181
  • 4
  • 26
  • 45
-1

like Lucas said, do it like this:

static Path path = Paths.get(System.getProperty("path"));

and then when you run your code, run it like this:

java myCoolCode.jar -Dpath=C:\\Users\\Me\\S2.txt
Dave
  • 867
  • 6
  • 11