Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string value to variable name | string value contain variable name

Double new_val = 10.0;
String a = "new";
String b = "val";
Double v1 = 25.0;
Double result = 0.0;

Public void getVal() {
    //String variable c contain double variable name
    String c = a+"_"+b;
    //I want to get c's value as 10.0 as its a variable already defined
    result = v1*c;
}

"c" String value contain variable name "new_val" and that is used for further

like image 880
mehal.ce Avatar asked May 26 '26 09:05

mehal.ce


2 Answers

If the question is, whether you can get the value of a variable knowing its name at runtime, then good news.... Yes for sure you can... you will need to do something called REFFLECTION...

which is allowing you as developer to make an instrocpection of the class and even "browse" all the info that the class is holding

in your case you need to find a "variable" (or Field) by the name and read its value...

look the doc for more info, and I would recommend you to consider if you really need to do this... normally reflection is intended to be used when you want to access info from another class and not about browsing yourself...

you can maybe redesign a little the application and define some constants and methods so other can see what you are exposing to them and making for them available...

Example:

public class Jung {
Double new_val = 10.0;
String a = "new";
String b = "val";
Double v1 = 25.0;
Double result = 0.0;

public void getVal() {
    // String variable c contain double variable name
    String c = a + "_" + b;
    Double cAsVal = 0.0;
    try {
        cAsVal = dale(c);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    result = v1.doubleValue() * cAsVal.doubleValue();
    System.out.println(result);
}

public static void main(String[] args) {
    Jung j = new Jung();
    j.getVal();
}

public Double dale(String c)
    throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    Field field = this.getClass().getDeclaredField(c);
    field.setAccessible(true);
    Object value = field.get(this);
    return (Double) value;
}
}
like image 99
ΦXocę 웃 Пepeúpa ツ Avatar answered May 27 '26 23:05

ΦXocę 웃 Пepeúpa ツ


What is you question?

If you want to do "25*c", it's like mutipling a Double (25) with a String ("new_val"). It wont work

like image 38
Souin Avatar answered May 27 '26 22:05

Souin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!