如何使用String变量的值调用对象的静态变量?

时间:2015-03-09 15:23:54

标签: java variables static

我创建了一个名为" Sample"的对象类。并且想要在创建对象的方法中访问与输入参数相对应的静态变量。

例如:

    // ____ FILE 1: Sample.java _______
package com.JavaProject;
import java.util.ArrayList;

public class Sample {

    String Sample_ID = "";
    ArrayList<String> Assay_ID = new ArrayList<String>();
    ArrayList<String> NCBI_ref = new ArrayList<String>();
    ArrayList<String> Call = new ArrayList<String>();
    ArrayList<String> Well = new ArrayList<String>();

}

// ____ FILE 2: Retreiver.java_______

public class Retreiver {
    public static void indexer (String Field){

        Sample sam = new Sample(); 
        sam.Sample_ID = "SAMPLE1"; 
        System.out.println(sam.Sample_ID); // This will print SAMPLE1 to console.
        System.out.println(sam.{Field}); // I want this to print the value of the field as per the variable's name. 
        }

    public static void main(String[] args) {
        String Field = "Sample_ID";
        indexer(Field);
    }
}

我喜欢Retreiver.Indexer打印出静态变量&#34; Sample_ID&#34;如方法输入参数&#34; Field&#34;中所定义。

即。如果我输入String Field =&#34; Assay_ID&#34;然后索引器会打印出样本的Assay_ID

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以使用反射来访问任何对象的字段。

public static void indexer (String field) {
    Sample sam = new Sample(); 
    sam.Sample_ID = "SAMPLE1"; 
    try {
        Field myField = Sample.class.getDeclaredField(field);
        myField.setAccessible(true);
        System.out.println(sam.Sample_ID); // This will print SAMPLE1 to console.
        System.out.println(myField.get(sam)); // I want this to print the value of the field as per the variable's name. 

    } catch (Exception e) {
        // Handle exception
    }
}