• 请不要在回答技术问题时复制粘贴 AI 生成的内容
q505507538
V2EX  ›  程序员

Java 的反射机制如何将属性名的字符串转成对应属性

  •  
  •   q505507538 · Dec 20, 2014 · 3496 views
    This topic created in 4188 days ago, the information mentioned may be changed or developed.
    public class test {

    private String string_1 = "aaaa";
    private String string_2 = "bbbb";
    private String string_3 = "cccc";
    private String string_4 = "dddd";
    private String string_5 = "eeee";

    public static void main(String[] args) {
    for(int i=1; i < 6; i++){
    String str = "string_" + i;
    System.out.println(str);
    }
    }
    }

    很明显这个输出结果是
    string_1
    string_2
    string_3
    string_4
    string_5
    可是我想要得到的是
    aaaa
    bbbb
    cccc
    dddd
    eeee
    应该如何实现
    2 replies    2014-12-21 02:52:01 +08:00
    qw7692336
        2
    qw7692336  
       Dec 21, 2014
    System.out.println(test.class.getDeclaredField(str).get(new test()))
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1056 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 18:59 · PVG 02:59 · LAX 11:59 · JFK 14:59
    ♥ Do have faith in what you're doing.