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

查看:29
本文介绍了是否可以在运行时在 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):

  • 将您的变量"表示为 Map 中的名称/值对.或者想出一些不需要真正动态变量的其他设计.
  • 使用在 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天全站免登陆