Java method to assign object field values with Reflection

后端 未结 3 1565
不知归路
不知归路 2021-01-05 02:37

I was wondering whether it would be possible to have something like the following in Java:

public class MyClass {
    private String name;
    private Intege         


        
3条回答
  •  迷失自我
    2021-01-05 03:19

    Though I'm at a loss as to why you would want to do it like that (since you already have getters and setters), try this:

    Field aField = getClass().getDeclaredField(aFieldName);
    aField.set(this, aValue);
    

    For more info, see this.

提交回复
热议问题