Java中如何使用名称访问变量?
我正在尝试在一个类中编写一个方法,该方法可以被调用多次,每次都会修改该类的一个字段。但是,如果我想修改它,我需要new
对象并将字段的值设置为它,但是如果在方法内部执行此操作,则引用似乎会丢失并且字段在打电话。
Public class A {
private Immutable a; //Immutable class
private Immutable b;
public void modify(Immutable k,int v) {
k=new Immutable(v); //Now I am trying to pass
//a and b as parameters but they remain unchanged
}
}
有没有办法将字段的名称传递到方法中(例如,将方法 modify(Immutable k, int v)
更改为 modify(String kName, int v)
,然后使用字段名称来访问它?
感谢您的任何输入!
I am trying to write a method in a class which could be invoked several times, each time modifying one of the class' fields. However, I need to new
the object and set the field's value to it if I want to modify it, but if do this inside the method, the reference seem to be lost and the field left unchanged after the calling.
Public class A {
private Immutable a; //Immutable class
private Immutable b;
public void modify(Immutable k,int v) {
k=new Immutable(v); //Now I am trying to pass
//a and b as parameters but they remain unchanged
}
}
Is there any way to pass the name of the field into the method (e.g., change the method modify(Immutable k, int v)
to modify(String kName, int v)
, then use the name of the field to access it?
Thanks for any inputs!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Java 不支持按名称调用或按引用调用,仅支持按值调用。您的 k 变量(方法参数)完全独立于类外部使用的任何变量(如果有的话)。
您可以使用反射来支持传递“a”或“b”(或 Field 对象),但您不应该这样做。
最好有两种方法:
如果它比单个构造函数调用更复杂,则将公共部分分解为公共方法。
Java does not support Call-by-name or call-by-reference, only Call-by-value. Your
k
variable (the method parameter) is completely independent from any variable used outside of the class (if there was one at all).You could use Reflection to support passing "a" or "b" (or a Field object), but you should not.
Better have two methods:
If it is more complicated than a single constructor call, factor the common part out to a common method.
如果需要通过 String 键访问变量,则应使用 地图。
If you need to access a variable by a String key, you should use a Map.
我的理解是,您正在尝试根据给定的整数(v)创建一个新的 Immutable 。在您现在的修改方法中,k 是一个临时引用。在这里设置值“k =”只会影响此方法中存储的引用,而不影响您调用修改时使用的任何引用。
您当前有这样的客户端代码:
并且您希望 k 会被更改。您真正想要的而不是第三行是:
假设事情确实更复杂,那么我需要更多信息来进一步帮助您。
What I understand is that you're trying to create a new Immutable given an integer (v). In your modify method right now, k is a temporary reference. Setting the value "k =" in here, only affects the reference stored here in this method, not whatever reference you called modify with.
You have client code like this currently:
and you're hoping that k will be changed. What you really want instead of the 3rd line is:
Assuming that things are really more complicated, then I would need more information to help you further.
使用价值持有者。
完成后,您可以从值持有者处获取刚刚创建的实例。
Use a value holder.
Once that is done you can get the instance you just created from the value holder.