通过它的名称获取变量的值:Java

时间:2015-03-26 12:13:15

标签: java reflection

我希望通过变量名来获得变量的值,我该如何实现呢?

private String firstName = "some xpath";
private String secondName = "some xpath";

public void findElement(String fName , String sName){ // fName = "firstName" , sName = "secondName"
driver.findElementByXPath(/*here goes reflection of fName*/);
driver.findElementByXPath(/*here goes reflection of sName*/);
}

由于

3 个答案:

答案 0 :(得分:4)

使用Reflection,您可以:

public void print(String fName , String sName) throws Exception {
    Field fNameField = this.getClass().getDeclaredField(fName);
    Field sNameField = this.getClass().getDeclaredField(sName);
    System.out.println(fNameField.get(this));
    System.out.println(sNameField.get(this));
}

答案 1 :(得分:1)

假设您的私有变量位于不同的类中,例如:

public class PrivateObject {
    private String firstName = "myFName";    
    private String secondName = "mySName";
}

你可以通过这样的反思来访问它们:

public void print(String fName , String sName){ // fName = "firstName" , sName = "secondName"
    PrivateObject p = new PrivateObject();
    try {
        Field fNameField = PrivateObject.class.getDeclaredField(fName);
        Field sNameField = PrivateObject.class.getDeclaredField(sName);
        fNameField.setAccessible(true);
        sNameField.setAccessible(true);
        String fNamefieldValue = (String) fNameField.get(p);
        String sNamefieldValue = (String) sNameField.get(p);
        System.out.println("fName = " + fNamefieldValue);
        System.out.println("sName = " + sNamefieldValue);
    } catch (Exception e) {
        e.printStackTrace();
    } 
}

答案 2 :(得分:-5)

此代码应该这样做:

private String firstName = "myFName";

private String secondName = "mySName";

public void print(String fName , String sName){

System.out.println(fName);
System.out.println(sName);

}

如果您希望它们位于同一行,您也可以使用System.out.print。