2015-03-25 39 views
0

一路:如何設置Java對象屬性像在JavaScript

我有一個數據模型對象在Java中,如:

class Model { 
    String name; 
    String email; 
} 

我想要做的就是動態地確定什麼屬性我想通過使用像JavaScript對象中的變量來設置;

String field = "name"; 

// This is what I try to achieve, not the real code. 
New Model().field = "according content"; 
or 
New Model()[field] = "according content"; 

感謝

+0

你可以使用反射 – 2015-03-25 00:47:55

+0

@ScaryWombat感謝您的回覆。你能給我舉一個簡單的例子嗎? – Kuan 2015-03-25 00:48:43

+0

看到我的回答低於 – 2015-03-25 00:50:33

回答

1

你可以反思在這個link

在這個例子中,他們有

public long chapters = 0; 

並能得到/設置爲

Field chap = c.getDeclaredField("chapters"); 
    out.format(fmt, "before", "chapters", book.chapters); 
    chap.setLong(book, 12); 
    out.format(fmt, "after", "chapters", chap.getLong(book)); 
+0

感謝您的幫助! – Kuan 2015-03-25 00:55:51