Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare Constant at Runtime

Tags:

java

I am reading from a file and setting values based on what I read from the file.

My question is: If I wanted to declare one of the retrieved values from the file as a constant how would i do that?

Edit: Say that value is an "int" for simplicity.

like image 327
thunderousNinja Avatar asked Dec 06 '22 22:12

thunderousNinja


2 Answers

I don't suppose you're looking for the final keyword?

final int foo = /* get it from the file */;
like image 72
Matt Ball Avatar answered Dec 10 '22 11:12

Matt Ball


Not sure what scope you want for this variable. The "final" keyword is about all you have to work with, as far as creating constants. It's easy enough to define a final local or instance variable in terms of runtime data, but declaring a static final class member is harder; you have to have the value available right when the class is loaded and initialized, so you have to do it somehow in a static initializer block:

public static final int CONSTANT;
static {
    CONSTANT = <something!>;
}
like image 27
Ernest Friedman-Hill Avatar answered Dec 10 '22 11:12

Ernest Friedman-Hill