根据用户输入选择对象的属性?

时间:2014-11-18 09:12:04

标签: java class

如何根据用户输入访问对象的属性?

例如我的班级是

class A{
  public String a;
  public String b;

  //constructor
  A(){
  a="first";
  b="second"; 
}

}

主程序是

public static void main(String[] args) {
  A a=new A();

  Scanner in= new Scanner(System.in);
  String x=in.next(); // the input it will be "a";
  String y= a.x;
  System.out.println(y);

  x=in.next(); // the input it will be "b";
  y= a.x;
  System.out.println(y);
}

2 个答案:

答案 0 :(得分:0)

尝试以下操作,您只需测试输入内容:

public static void main(String[] args) {
  A a=new A();

  Scanner in= new Scanner(System.in);
  String x=in.next(); 
  if(x.equals("a")){  // the input is "a";
    String y= a.a;
    System.out.println(y);
  }
  else if(x.equals("b")){ // the input is "b";
    String y= a.b;
    System.out.println(y);
  }
  else System.out.println("Input a or b please !!!");
}

如果您编写a.x,编译器将获取x作为类A的变量,而不是输入值。

答案 1 :(得分:-1)

您需要java reflection

import java.lang.reflect.*;
import java.util.*;

class A{
   public String a;
   public String b;

   //constructor
   A(){
      a="first";
      b="second"; 
   }

   public static void main(String[] args) throws Exception {
      A a=new A();
      Class c = A.class;

      Scanner in= new Scanner(System.in);
      String x=in.next(); // the input it will be "a";

      Field f = c.getField(x);
      String y = (String) f.get(a);

      System.out.println(y);

      x=in.next(); // the input it will be "b";

      f = c.getField(x);
      y = (String) f.get(a);

      System.out.println(y);
  }
}