是否可以在Java中在运行时创建变量? [英] Is it possible to create variables at runtime in Java?

查看:132
本文介绍了是否可以在Java中在运行时创建变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,假设我想提取 String [] fruits = {Pear,Banana,Apple}; 分为三个单独的变量,例如:

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.

以前曾多次提出类似的问题,但真正的答案从未给出,因为OP真正需要的是使用不同的方法。那没关系,但这有可能吗?

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.

推荐答案


是否可以在Java中在运行时创建变量?

Is it possible to create variables at runtime in Java?

简单的答案是否。

Java是一种静态语言,不支持注入新的变量声明到现有的编译程序中。有其他选择(按有用性降低/难度增加的顺序):

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):


  • 将<变量表示为<$中的名称/值对C $ C>地图。或者提出一些不需要需要真实动态变量的其他设计。

  • 使用在JVM上运行并可从Java调用的脚本语言。

  • 使用某种模板机制生成包含声明的新源代码,并动态编译和加载它。

  • 使用字节码操作库(例如BCEL)动态创建类文件,然后动态加载它们。

  • Represent your "variables" as name / value pairs in a Map. Or come up with some other design that doesn't require real dynamic variables.
  • Use a scripting language that runs on the JVM and is callable from Java.
  • Use some kind of templating mechanism to generate new source code containing the declarations, and compile and load it dynamically.
  • Use a byte code manipulation library (e.g. BCEL) to create class files on the fly and then dynamically load them.

第一种方法是最好的。 Java是一种静态语言,如果你不打它,效果最好。如果这对你来说是一个问题,也许你使用了错误的语言。

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 ...

这篇关于是否可以在Java中在运行时创建变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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