2016-07-23 119 views
2
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」的字符串值包含變量名「new_val」和用於進一步將字符串值轉換爲變量名稱|字符串值包含變量名

+0

'結果= V1 * C;'這是不是一個有效的語義,因爲v1是數字,c是字符串.. –

回答

3

你如果問題是,是否能得到一個變量在運行時知道它的名字的價值,那麼好消息是....肯定,你可以...你需要做一些所謂的REFFLECTION。 ..

它可以讓你的開發人員,使類的instrocpection,甚至「瀏覽」該類持有

你的情況

你需要找到一個「變量」的所有信息(或現場)的名稱並閱讀其值...

查看文檔以獲得更多信息,我會建議你考慮一下,如果你真的需要這樣做...通常反射是用來當你想從另一類訪問的信息,而不是關於瀏覽自己...

你也許可以重新設計一個小應用程序並定義了一些常量和方法,這樣其他可以看到你所暴露給他們,並讓他們提供...

例子:

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

感謝男人,代碼工作得很好 –

+0

歡迎您! –

0

什麼是你的問題?

如果你想要做「25 * c」,就像是將Double(25)與一個String(「new_val」)重疊。它不會工作

+0

我想將字符串值(「c」)轉換爲變量名稱(Double new_val) –

+1

仍然不清楚..你想創建一個名稱是在一個字符串值的變量? –

+0

你不能。你想如何在Double中轉換字符串? 例如,如何將String str =「myString」轉換爲Double? 另一個方向起作用。確實,你想將Double dbl = 28轉換爲String,你可以使用String.valueOf(dbl)。它將返回一個字符串str2 =「28」 – Souin

0

如果我是正確的,你不能在基於Java中的另一個變量值代碼中的變量名稱。如果你需要在變量的字符串值,你應該創建域類,例如:

class myVariable{ 
    String name; 
    int value; 
} 
+0

我想將字符串值(「c」)轉換爲變量名稱(Double new_val) –

0

我想字符串值(「C」)轉換爲變量名(雙人間new_val)

很高興看到reflection可以用來完成工作。

對於你的情況,Map也可以爲你做。

public static void main(String args[]){ 
    HashMap<String, Double> map = new HashMap<String, Double>(); 
    map.put("new_val", 10.0); 

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

    //String variable c contain double variable name 
    String c = a+"_"+b; 
    //String variable c used for calculation 
    result = v1 * map.get(c); 

    System.out.println(result); 
} 

檢查To use a string value as a variable name瞭解更多詳情。