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? 回答1: Here's how