Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting variables by name in Java

I'm looking to implement something in Java along the lines of:

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(){}
}

...where a variable is set based on the variable name without the variable names hard-coded and without using any other data structures. Is this possible?

like image 541
Mat Kelly Avatar asked Nov 09 '08 22:11

Mat Kelly


People also ask

How do you assign a variable to a name in Java?

For variables, the Java naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word. Variables in Java are not allowed to contain white space, so variables made from compound words are to be written with a lower camel case syntax.

How do you dynamically name a variable in Java?

There are no dynamic variables in Java. Java variables have to be declared in the source code1. Depending on what you are trying to achieve, you should use an array, a List or a Map ; e.g. It is possible to use reflection to dynamically refer to variables that have been declared in the source code.

How do you set a variable in Java?

To declare (create) a variable, you will specify the type, leave at least one space, then the name for the variable and end the line with a semicolon ( ; ). Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false).

Can you use in Java variable name?

Rules to Declare a VariableBlank spaces cannot be used in variable names. Java keywords cannot be used as variable names. Variable names are case-sensitive. There is no limit on the length of a variable name but by convention, it should be between 4 to 15 chars.


1 Answers

Here's how you might implement setAttribute using reflection (I've renamed the function; there are different reflection functions for different field types):

public void setIntField(String fieldName, int value)
        throws NoSuchFieldException, IllegalAccessException {
    Field field = getClass().getDeclaredField(fieldName);
    field.setInt(this, value);
}
like image 87
Chris Jester-Young Avatar answered Sep 22 '22 11:09

Chris Jester-Young