[英]How to create an instance of a class with a variable string name in Java?
[英]Java - Create instance of a class with String as name
我想创建一些类的实例,就像:
Country ger = new Country();
Country usa = new Country();
...
等等。 因为我想对大量对象执行此操作,所以我希望使用文本文件创建实例名称的实例,这些文件列出了这些国家/地区标签并在此列表中进行迭代。 我熟悉Java反射概念,但是我不想为每个对象创建单个类,因为我只想缩短这些声明。
有什么办法吗?
提前致谢
向Country
添加一个名称变量,并通过构造函数对其进行初始化。 或使用地图。
因此,首先让我们关注您的国家/地区类别。 根本问题是您想制作每个对象代表一个国家的Country对象。 为此,您需要在Country类中使用一个String作为参数的构造函数,以便在Main程序中可以执行以下操作:
Country ger = new Country("Germany");
Country usa = new Country("USA");
但是,为此,您首先需要确保Country类具有一个实例变量,该实例变量可以存储每个对象的国家/地区。 因此,Country类至少需要具备以下条件:
public class Country {
//Each object holds a variable called country, which is the name of the country
private String country;
//This constructor takes the name you enter in brackets and sets country to this name
public Country(String name) {
country = name;
}
}
现在我们准备制作代表不同国家的国家对象。 由于您要从文本文件(.txt)输入国家/地区,因此您需要制作一些工具来处理相关文件。 为了简单起见,我假设文本文件中只有国家名称用换行符隔开。 您可以扩展Country类,使其包含主要方法以及一些相关的导入:
import java.io.*;
import java.util.Scanner;
public class Country {
//Each object holds a variable called country, which is the name of the country
private String country;
//This constructor takes the name you enter in brackets and sets country to this name
public Country(String name) {
country = name;
}
public static void main(String[] args) {
//This represents the file you want to access
File countryFile = new File("path-of-text-file-goes-here");
Scanner input = null; //this tool will allow you to read from the file
try {
//we must initialize the file read tool in a try block
input = new Scanner( new FileInputStream(countryFile) );
}
catch (FileNotFoundException e) {
System.out.println("Error accessing the file. Exiting...");
System.exit(0);
}
//initialize an empty String and we will put all the countries in the file
//into our program by first putting it in a String separated by spaces
String inputText = "";
while (input.hasNext()) //tests to see whether input has a word left
inputText += input.next() + " "; //if so, add it to the String and add a space
//Here we are creating an array of Strings, where each indice is one word from inputText
// the split(" ") method returns an array of characters separated by spaces
String[] inputTextArray = inputText.split(" ");
//initialize a Country array to the length of words in inputText
Country[] countryObject = new Country[inputTextArray.length];
//for each word in inputTextArray, initialize each indice in countryObject
//with a new Country("each-indice-of-inputTextArray-will-be-placed-here-one-by-one")
for (int i = 0; i < countryObject.length; i++)
countryObject[i] = new Country(inputTextArray[i]);
}
}
数组countryObject现在应该用Country对象填充,其中每个对象都是您在文本文件中键入的国家。 希望这会有所帮助,让我知道您是否不清楚或我误解了这个问题。 谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.