Java 可以在运行时创建变量吗?
例如,假设我想将 String[]fruits = {"Pear", "Banana", "Apple"};
“提取”到三个单独的变量中,例如:
for (int i=0; i != fruits.length; ++i) {
// of course there's no eval in Java
eval("String fruit + i = " + fruits[i] + ";");
}
// ie: code that creates something equivalent to the following declarations:
String fruit0 = "Pear";
String fruit1 = "Banana";
String fruit2 = "Apple";
我怎样才能做到这一点,忽略“你到底为什么要这么做?”你可能会被催促问我这个问题。
类似的问题以前已经被问过很多次,但从未给出真正的答案,因为OP真正需要的是使用不同的方法。很好,但这可能吗?
我研究过反射,似乎没有任何方法可以让我向实例添加额外的字段,更不用说动态创建局部变量了。
For example, say I wanted to "extract" String[] fruits = {"Pear", "Banana", "Apple"};
into three separate variables, eg:
for (int i=0; i != fruits.length; ++i) {
// of course there's no eval in Java
eval("String fruit + i = " + fruits[i] + ";");
}
// ie: code that creates something equivalent to the following declarations:
String fruit0 = "Pear";
String fruit1 = "Banana";
String fruit2 = "Apple";
How could I do that, ignoring the "Why the heck would you want to do that?" question that you might be urged to ask me.
Similar questions have been asked many times before, but the real answer was never given, because what the OP really needed was to use a different approach. That's fine, but is this possible at all?
I have looked at reflection and it doesn't seem like there are any methods that would allow me even to add extra fields to an instance, let alone dynamically create locals.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
简单的答案是否定的。Java
是一种静态语言,不支持将新变量声明注入到现有的已编译程序中。还有其他选择(按照实用性递减/难度递增的顺序):
Map
中的名称/值对。或者提出一些不需要真正的动态变量的其他设计。第一种方法是最好的。 Java 是一种静态语言,如果你不对抗它,效果最好。如果这对您来说是个问题,也许您使用了错误的语言。
最后两个是困难/复杂的并且具有显着的性能成本。他们几乎肯定不会提供帮助......
The simple answer is No.
Java is a static language and does not support the injection of new variable declarations into an existing compiled program. There are alternatives (in order of decreasing usefulness / increasing difficulty):
Map
. Or come up with some other design that doesn't require real dynamic variables.The first approach is the best. Java is a static language, and works best if you don't fight it. If this is a problem for you, maybe you are using the wrong language.
The last two are difficult / complicated and have significant performance costs. They are almost certainly not going to help ...
问题不是你为什么要这样做,而是“你打算用它做什么?”。因此,假设在运行时名为“fruits2”的变量神奇地出现在方法的堆栈上。现在怎么办?您必须在编译时知道它的名称才能利用它。反射不会帮助您访问局部变量。
无论如何,如果您描述更详细的用例,我会很感兴趣。
The question is not why you want to do it but 'what are you going to do with it?'. So suppose at runtime variable with the name
fruits2
magically appeared on the stack of your method. Now what? You had to know its name at compile time to take advantage of it. Reflection will not help you access local variables.Anyway, I would be interested if you described more detailed use case.
你提出问题的方式,人们不会理解你在问什么。我相信(如果我确实理解)您的问题的答案(应该表述为:“是否可以在运行时动态创建变量”)是“不像您提出的那样”。
你是对的,Java 中没有与 javascript 类似的东西(非常强大,但速度慢且充满危险的“eval”函数),而这正是你需要让它来做你希望做的事情。
最接近的是哈希图(实际上非常接近),您可以在运行时指定键,然后设置值。它的用途相当广泛,因为您可以拥有一张地图,允许您在字段中存储任何类型。
The way you phrased your question, people won't understand what you're asking. I believe (if I DO understand) the answer to your question (which should be phrased: "is it possible to dynamically create variables at run time") is "not as you've presented it".
You're right, there's no analog to javascript's (very powerful, but slow and fraught with hazards "eval" function) in Java, and that is precisely what you would need to get this to do what you're hoping to do.
The closest that exists is a hashmap (which is actually pretty close) where you can designate the key at run time, and then set the value. It's fairly versatile as you can have an map that will allow for whatever type you want stored in the field.
您将无法修改已加载到 JVM 中的类。但是,您可以想象使用 ASM < http://asm.ow2.org/ >或BCEL< http://commons.apache.org/bcel/>动态生成具有动态定义字段的新类。
麻烦多于其价值。说真的,只要使用 HashMap 就可以了!
You're not going to be able to modify a class that's already been loaded into the JVM. However, you could conceivably use ASM < http://asm.ow2.org/ > or BCEL < http://commons.apache.org/bcel/> to dynamically generate a new class that has the dynamically-defined fields.
Way more trouble than it's worth. Seriously, just use a HashMap!
Janino 对你有用吗?
这是一些代码。我认为它接近你想要的,但我不确定。
}
Would Janino be useful for you?
Here's some code. I think it's close to what you want, but I'm not sure.
}
是的,例如,请参阅 Lombok 库,特别是 @log4j 注释,它将日志变量注入到类中
Yes, for example, see Lombok library and specifically @log4j annotation that injects the log variable to the class
您能否详细说明一下,不确定您在这里做了什么不同的事情。当然,您可以创建三个不同的字符串。不过我相信java中的语法是 string xx = new string("DDFD");
编辑:
我的意思是,你想在这里改变什么。您可以动态分配内存,因此可以动态创建“变量”。但是,您不能以原始方式创建“变量”,例如“int x = 0;”在运行时,但是您可以在运行时将节点添加到链接列表、调整数组大小等。
Can you perhaps elaborate, not sure what you're doing different here. Of course you can create three different strings. However i believe the syntax in java is string xx = new string("DDFD");
Edit:
By this i mean, what are you trying to change here. You can allocate memory dynamically therefore you can create "variables" dynamically. HOWEVER you cannot create a "variable" in the primitive fashion such as "int x = 0;" in run time, however you can add nodes to linked lists, resize arrays, etc during run time.