I'm basically a beginner in Java and I am trying to figure out this problem:
my project uses (integer)constant through many classes and I need to set up this constant from file/argument of programm and I have no idea how. I could remove "final" statement but that is against all conventions.
How to resolve this? What is best way to avoid it? Please help me :)
short example:
public class App {
public static final int k;
public static void main( String[] args ) {
k = Integer.parseInt(args[0]); // does not work ... sure but how?
}
}
EDIT: public STATIC void main ... (it was missing static)
You can only use this kind of functionality within the static { }
block.
I'd recommend making the constant itself private, and accessible only through public static
getter methods. This should be a suitable architecture.
You need to use a static{}
block:
public class App {
public static final int k;
static {
String kvalue = "";
try
{
// Insert some code to open a file and read a value from it.
kvalue = "<value from file>";
}
catch( Exception e )
{
// handle any exceptions opening the file
}
finally
{
k = Integer.parseInt( kvalue );
}
}
public static void main( final String[] args ) {
// do stuff
}
}
Alternatively, you could have each class that requires this value access to a shared pool of data, the ApplicationContext
, where the value X
would reside as a constant:
public final class ApplicationContext {
public static abstract class Worker {
private final ApplicationContext mApplicationContext;
public Worker(final ApplicationContext pApplicationContext) {
this.mApplicationContext = pApplicationContext;
}
public final ApplicationContext getApplicationContext() {
return this.mApplicationContext;
}
}
private final int mX;
ApplicationContext(final String[] pArgs) {
this.mX = pArgs[0];
}
public final int getX() {
return this.mX();
}
}
By having all relevant classes extend ApplicationContext.Worker
, we can ensure access to the constant value without having to rely upon a static
implementation because all classes will receive a reference to ApplicationContext
upon construction.
它不起作用,因为static final
变量只能在静态块中初始化。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.