在 class Java 中获取第 n 个对象

Get nth object in class Java

如果我有这个代码:

public class Foo{
    public static void main(String[] args){
    String hello = "Hello World";
    int num = 7;
        }
    }

如果我想打印出 String hello 和 int num,我通常会这样做:

System.out.println(hello);
System.out.prinln(num);`

但是,我可以用不同的方式访问 hello 和 num 吗,比如:

Foo(0); // for String hello
Foo(1); //for int num

由于 hellonum 是在 main() 中声明的,所以您现在可以使用 class 名称访问它,因为它们不会超出 main().

我猜你可能要求的是数组:

public static void main(String[] args) {
    Object[] foo = {"hello world", 7};
    System.out.println(foo[0]);//hello world
    System.out.println(foo[1]);//7
}