繁体   English   中英

如何使用另一个字符串打印另一个 class 的字符串变量来调用该变量? (Java)

[英]How to print a String variable of another class using another String to call that variable? (JAVA)

我有这个规范,通过使用字符串调用该变量的 static 实例,从特定的 class 获取变量值。

假设我有一个名为 Sample 的 class 和另一个名为 testValue 的 class。 testValue 有一个公共的 static 最终字符串测试,我必须打印它的值。 当我尝试以这种方式打印时,output 是“测试值”。

public class Sample{
    public static void main(String args[]){
        System.out.println(testValue.test);
    }
}
class testValue{
    public static final String test = "Test Value";
}

现在我想通过其他字符串调用它来打印“测试值”。 是这样的:

public class Sample{
    public static void main(String args[]){
        String new = "test";
        System.out.println(testValue.new);
    }
}
class testValue{
    public static final String test = "Test Value";
}

但这会导致错误,因为 testValue class 中未定义新的。是否有其他方法可以执行此特定操作。 它有点奇怪,但这是我想要调用测试变量的确切方式。 提前致谢。

您可以在 class testValue 中为所需变量定义一个 getter

public class Sample{
    public static void main(String args[]){
        String new = testValue.getTest();
        System.out.println(new);
    }
}
class testValue{
    public static String test = "Test Value";

    public static String getTest(){
        return test;
    }
}

这将打印“测试值”。 为了不破坏封装的最佳实践,您还应该定义一个 setter 并像这样将变量设为私有

public class Sample{
    public static void main(String args[]){
        String new = testValue.getTest();
        System.out.println(new);
    }
}
class testValue{
    private static String test = "Test Value";

    public static String getTest(){
        return test;
    }

    public static void setTest(String test){
        this.test = test;
    }
}

你可能想这样做,因为它在 JavaScript 中工作。在 Java 中,你不能正常做这样的事情。 但是你可以使用反射,这是不推荐的获取字段值的方法:

public class TestClass {
    public static final String field = "Test Value";
}
TestClass testClass = new TestClass();
Class<TestClass> personClass = TestClass.class;
Field field = personClass.getField("field");
String fieldValue = (String) field.get(testClass);
System.out.println(fieldValue);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM