Setting variables by name in Java

I'm looking for something to implement in Java:

class Foo{
 private int lorem; //
 private int ipsum;      

 public setAttribute(String attr,int val){
  //sets attribute based on name
 }

 public static void main(String [] args){
  Foo f = new Foo();
  f.setAttribute("lorem",1);
  f.setAttribute("ipsum",2);
 }

 public Foo(){}
}

... set the variable according to the variable name, which is hard coded and does not use any other data structure Is that possible?

Solution

Here is how to use reflection to implement setAttribute (I have renamed this function; different field types have different reflection functions):

public void setIntField(String fieldName,int value)
        throws NoSuchFieldException,illegalaccessexception {
    Field field = getClass().getDeclaredField(fieldName);
    field.setInt(this,value);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>