使用String值创建变量名 [英] Creating a variable name using a String value

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

问题描述

这是一个简单的问题(我认为)

This is a simple question (I think)

假设我有这个代码(假设我有一个狗类)

Lets say I have this code (Assuming I have a dog class)

String name = "dog";
dog name = new dog();

如何让java识别名字为字符串并命名对象狗?

How can I get java to recognize name as a String and name the object dog?

推荐答案

虽然你可以做一些脚本语言,如PHP(和这个问题经常被许多PHP程序员Java),这不是Java的工作原理,事实上变量名是一个不太重要的,你可能会意识到,甚至几乎不存在后编译代码。更重要的是什么和什么是关键是变量引用 - 在程序中的特定点获得访问特定对象的能力,你可以有Strings通过使用一个地图作为一种方式。

While you can do what you're trying in some scripting languages such as PHP (and this question is often asked by many PHP programmers who start Java), this is not how Java works, and in fact variable names are a much less important than you may realize and hardly even exist after code is compiled. What is much more important and what is key are variable references -- the ability to gain access to a particular object at a particular point in your program, and you can have Strings refer to objects easily by using a Map as one way.

例如

Map<String, Dog> dogMap = new HashMap<String, Dog>();
dogMap.put("Fido", new Dog("Fido"));

Dog myPet = dogMap.get("Fido");

或者你可以通过其他方式获取对象的引用,例如通过数组,ArrayLists,LinkedList,

Or you can gain references to objects in many other ways such as via arrays, ArrayLists, LinkedLists, or several other collectinos.

编辑

您表示:

Edit
You state:

事情是,在我的代码中,我将使用一个方法来创建对象,对象的名称是任意的,但我需要它是动态的,因为它不是临时的,所以实际上对象的名称必须更改,否则我将写入先前声明的对象。

The thing is that in my code I am going to be using one method to create objects, the name of the object is arbitrary but I need it to be dynamic because it wont be temporary, so the actually name of the object has to change or I will be writing over the previously declared object.

这正是我的意思说,变量的名称不像你认为的那么重要。变量名是 不是 对象名称(这实际上不存在)。

This is exactly what I meant when I said that the name of the variable is not as important as you think it is. The variable name is not the "object name" (this really doesn't exist in fact).

例如,如果你在名为Fido的变量中创建一个狗,然后将它分配给一个名为spot的新变量,尽管这两个变量具有不同的名称,它们将引用完全相同的对象:

For example if you create a dog in a variable named Fido, and then assign it to a new variable named spot, both variables, despite having different names will refer to the very same object:

Dog fido = new Dog;
Dog spot = fido; // now fido and spot refer to the same object

如果你想给变量一个名字考虑给类一个名字属性:

If you want to give a variable a "name" consider giving the class a name property:

class Dog {
   private String name;

   public Dog(String name) {
      this.name = name;
   }

   public String getName() {
      return name;
   }
}

现在你可以给每个Dog对象自己的)唯一名称。

Now you can give each Dog object its own (semi) unique name if you wish.

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

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