Home > Enterprise >  How to print a String variable of another class using another String to call that variable? (JAVA)
How to print a String variable of another class using another String to call that variable? (JAVA)

Time:04-06

I have this specification to get the variable values from a particular class by calling the static instance of that variable using a String.

Lets say I have a class called Sample and another class called testValue. testValue has a public static final String test, whose value I have to print. When I try to print it in this way the output is "Test Value".

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

Now I want to print "Test Value" by calling it through some other string. Something like this:

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";
}

But this gives an error as new is not defined inside testValue class. Is there any other way to do this particular thing. Its a bit weird but this is the exact way I want to call the test variable. Thanks in advance.

CodePudding user response:

You probably want to do it as it works in JavaScript. In Java, you can't do such a thing normally. But you can use reflection, which is not recommended way of getting field value:

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);

CodePudding user response:

You can define a getter for the desired variable inside the class testValue

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;
    }
}

This will print "Test Value". For the best pratice to not break encapsulation you also should define a setter and making the variable private like so

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;
    }
}
  • Related