透過java的反射可以實現,程式碼:
public class User { String userId; String userName; public static void main(String[] args) { User u = new User(); u.set("userId", "001"); u.set("userName", "xiaoming"); System.out.println(u);//User{userId="001", userName="xiaoming"} } public void set(String field, Object keyWord) { try { Field f = getClass().getDeclaredField(field); f.setAccessible(true); f.set(this, keyWord); } catch (Exception e) { e.printStackTrace(); } } @Override public String toString() { return "User{" + "userId="" + userId + "\"" + ", userName="" + userName + "\"" + "}"; }}
有問題請追問
透過java的反射可以實現,程式碼:
public class User { String userId; String userName; public static void main(String[] args) { User u = new User(); u.set("userId", "001"); u.set("userName", "xiaoming"); System.out.println(u);//User{userId="001", userName="xiaoming"} } public void set(String field, Object keyWord) { try { Field f = getClass().getDeclaredField(field); f.setAccessible(true); f.set(this, keyWord); } catch (Exception e) { e.printStackTrace(); } } @Override public String toString() { return "User{" + "userId="" + userId + "\"" + ", userName="" + userName + "\"" + "}"; }}
有問題請追問