[英]How to initialize constant such as “public static final Integer” in java from args[] in main method (or any)
I'm basically a beginner in Java and I am trying to figure out this problem: 我基本上是Java的初学者,并且我试图找出这个问题:
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. 我的项目通过许多类使用(整数)常量,我需要从programm的文件/参数中设置此常量,但我不知道如何。 I could remove "final" statement but that is against all conventions. 我可以删除“ final”语句,但这违反所有约定。
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. 您只能在static { }
块中使用这种功能。
I'd recommend making the constant itself private, and accessible only through public static
getter methods. 我建议将常量本身设为私有,并且只能通过public static
getter方法访问。 This should be a suitable architecture. 这应该是一个合适的体系结构。
You need to use a static{}
block: 您需要使用static{}
块:
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: 或者,您可以让每个需要此值访问共享数据池ApplicationContext
,其中值X
将作为常量驻留在其中:
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. 通过使所有相关的类扩展ApplicationContext.Worker
,我们可以确保访问常量值而不必依赖static
实现,因为所有类在构造时都会收到对ApplicationContext
的引用。
它不起作用,因为static final
变量只能在静态块中初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.