简体   繁体   English

如何使用作为命令参数传输的 String 变量到 Java 中另一个类的实例?

[英]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.

相关问题 如何使用Java中另一个类的变量 - How can I use a variable from another class in Java 如何使用类运行器中的变量在另一个类的方法中使用? (BlueJ,Java) - How can I use a Variable from a Class Runner to use in a Method in another Class? (BlueJ, Java) 如何在Java中使用一个方法在一个类中创建另一个实例? - How can I use a method in one class to create an instance of another in Java? 如何在另一个 class 中获取实例? 在 java - How can I get an instance in another class? in java 如何在 java 中的另一个 class 的变量上使用运算符 - How can you use operators on a variable from another class in java Java 8:如何将静态方法用作另一个方法的参数? - Java 8: How can I use a static method as a parameter for another method? 如何从另一个 class I Java 访问变量 - How can I acces variable from another class I Java 我如何在java中使用运行命令选项设置字符串变量? - How i can set a string variable with a run command option in java? 如果将类用作类型参数,如何在参数化的类中创建此对象的实例? - If I use a class as a type parameter, how can I create an instance of this object within the parameterized class? 如何在 Java 中的另一个 class 中使用来自 class 的变量 - How can I use variables from a class in another class in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM