[英]How can I use the String variable transferred as the command parameter to a instance of another class in Java?
How can I use the String variable transferred as the command parameter to a instance of another class in Java?如何使用作为命令参数传输的 String 变量到 Java 中另一个类的实例?
Like this:像这样:
public class NBody {
public static void main(double T, double dt, String filename) {
In filename = new In();
filename.readInt();
}
}
It notified as:它通知如下:
NBody.java:3: filename is already defined in main(double,double,java.lang.String) In filename = new In(); NBody.java:3: filename 已经在 main(double,double,java.lang.String) 中定义在 filename = new In();
What you are trying to do is define multiple variables which have the same name, so it is impossible.您要做的是定义多个具有相同名称的变量,因此这是不可能的。 Imagine if it was possible, how would java runtime know which one you reference?想象一下,如果可能的话,java 运行时如何知道您引用的是哪一个?
However if what you want is reference a variable which name's given as command line argument.但是,如果您想要的是引用一个名称作为命令行参数给出的变量。 You can use Reflection.您可以使用反射。
import java.lang.reflect.*;
public class Main {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Field staticFieldMInt = Custom.class.getField("mInt"); // this can be argument
Integer mInt = (Integer) staticFieldMInt.get(null); // null because it is a class property.
System.out.println(mInt); // prints 10
}
}
public class Custom {
public static Integer mInt = 10; // this could be any type
}
You can't use runtime information (the content of a variable) to determine the name of a local variable.您不能使用运行时信息(变量的内容)来确定局部变量的名称。 Variable names are a compile-time thing, not a runtime thing.变量名是编译时的事情,而不是运行时的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.