使用字符串代替变量名称 [英] Use string in place of variable name

查看:165
本文介绍了使用字符串代替变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有一个名为xyz的Java变量。
然后我定义一个字符串,其中包含我想要使用的命名变量的值。

If you have a Java variable named xyz. Then later on I define a string which has the value of the named variable I want to play with.

String x="xyz";

如何让Java将String x识别为变量xyz的指针?

How do I get Java to recognise that String x as a pointer to variable xyz?

一个任意的例子:

JButton a= new JButton();

稍后......

String x="a";

我现在要说的是

JButton called string x.setPreferredSize(new Dimension(40,30));


推荐答案

一般来说,如果你想访问一个变量这样,你必须使用反射,这是较慢且有潜在危险。

In general, if you want to access a variable in this way, you have to use Reflection, which is slower and potentially dangerous.

但是,由于你有一个非常具体的场景,我会采取不同的方法。为什么不把你的按钮或其他元素放到地图中,键是字符串:

However, since you have a very specific scenario in mind, I'd take a different approach. Why not put your buttons or other elements into a map, with keys that are strings:

Map<String, JComponent> currentComponents = new HashMap<String, JComponent>();

currentComponents.put("a", new JButton());

String x = "a";

currentComponents.get(x).setPreferredSize(new Dimension(40,30));

这篇关于使用字符串代替变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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