如何在Java中动态创建类的对象?

时间:2016-10-15 16:42:02

标签: java object dynamic

目前我有一个可以静态创建类对象的项目:

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)

3 个答案:

答案 0 :(得分:1)

lets say u get the information from some text box. then your code would look like this:

// 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);

答案 1 :(得分:1)

Try using a simple array combined with a for loop to create a size of your chosing

Song song[(number of songs)];
for(x=0;x<=(number of songs);x++)
{
    song[x] = new Song();
}

To access your song you would do

song[(song number)].setTitle();

答案 2 :(得分:1)

First of all you might want to have an alternate constructor inside your Song class...

private String name;
private int rating;
private double price;

public Song( String name, int rating, double price )
{
    setName(name);
    setRating(rating);
    setPrice(price);
}

// setters/getters

Seems like you're wanting something like this...

  1. Store user input using a list – check out the docs for java.util.Collections
  2. Use a loop to instantiate Song objects – also storing them in a list.
  3. Use the List

Your loop might look a little like this...

List<String[]> userInput = new ArrayList<>();
// Fill list with user input
List<Song> songList = new ArrayList<>();

for( String[] tokens : userInput )
{
    String name = tokens[0];
    int rating = Integer.parseInt(tokens[1]);
    double price = Double.parseDouble(tokens[2]);

    songList.add( new Song(name, rating, price) );
}

// Do something with songList