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

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

问题描述

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

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 将 name 识别为 String 并将对象命名为 dog?

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

推荐答案

虽然您可以在某些脚本语言(例如 PHP)中执行您正在尝试的操作(许多开始 Java 的 PHP 程序员经常会问这个问题),但是这这不是 Java 的工作方式,事实上变量名远没有你意识到的那么重要,甚至在代码编译后几乎不存在.更重要和关键的是变量引用——在程序中的特定点获得对特定对象的访问的能力,并且您可以使用字符串轻松地引用对象地图作为一种方式.

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、LinkedLists 或其他几个集合.

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

编辑
你说:

问题是在我的代码中我将使用一种方法来创建对象,对象的名称是任意的,但我需要它是动态的,因为它不会是临时的,所以对象的实际名称有更改,否则我将覆盖之前声明的对象.

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.

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

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