目前我有一个可以静态创建类对象的项目:
Song song1 = new Song();
song1.setTitle("Paint it Black");
song1.setRating(4);
song1.setPrice(0.99);
Song song2 = new Song("Hey Jude",4.99);
song2.setRating(10);
这工作得很好,但我想这样做,这样我就可以创建对象,而不必将每个对象硬编码到我的程序中,因为正如你可以想象的那样,它会变得很长。有什么办法可以实现这个目标吗?
本质上,而不是
Song song1 = new Song();
Song song2 = new Song();
Song song3 = new Song();
Song song4 = new Song();
Song song5 = new Song();
...
Song songN = new Song();
有一个算法可以根据用户输入为我创建我的对象(song1、song2、song3...songN)
最佳答案
假设您从某个文本框中获取信息。 那么你的代码将如下所示:
// create only once
List<Song> songs = new ArrayList<>();
//at add song button click
Song song = new Song();
song.setTitle(titleTextBox.getText());
song.setRating(ratingTextBox.getText());
song.setPrice(priceTextBox.getText());
songs.add(song);
// add the toString() method to the Song class
// print the list to see the elements of the list
System.out.println(songs);
关于java - 如何在Java中动态创建类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40061635/