在Java中按名称设置变量 [英] Setting variables by name in Java

查看:123
本文介绍了在Java中按名称设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用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?

推荐答案

以下是使用反射实现 setAttribute 的方法(我已重命名该函数;对于不同的字段类型有不同的反射函数):

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);
}

这篇关于在Java中按名称设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆