Java 动态创建实例名称?
考虑以下不起作用的情况。应该做些什么才能使它起作用。我想动态创建song、s1、s2、s3等的实例。我知道song中没有对象的方法,但我也不能将s1、s2、s3分配给songJava 动态创建实例名称?,java,Java,考虑以下不起作用的情况。应该做些什么才能使它起作用。我想动态创建song、s1、s2、s3等的实例。我知道song中没有对象的方法,但我也不能将s1、s2、s3分配给song int i; String s; for(i=0; i < 4; i++) { //Stuff to get song info omitted. Object thisSong = s + Integer.toString(i);//append 1 to s thisSong =
int i;
String s;
for(i=0; i < 4; i++)
{
//Stuff to get song info omitted.
Object thisSong = s + Integer.toString(i);//append 1 to s
thisSong = new Song(title, artist, playTime, fileName);//create new object
System.out.println(thisSong.getTitle());// Error here. getTitle() is undefined.
}
}变量thisSong具有对象类型,但对象类型没有getTitle()方法。
您所需的一切只需将这首歌投下如下歌曲类型:
Song song = (Song)thisSong;
song.getTitle();
for (int i=0, i < 4, i++){
String title = s + i; // no need to use Integer.toString() because using '+' with a String(s) turns i into a String too
Song mySong = new Song(title, artist, playTime, fileName);
System.out.print( mySong.getTitle() );
}
或
我不确定你想达到什么目的。另一个答案是建议选角,但如果你试着选这首歌,你会得到一个
ClassCastException
因为您在thisSong
中存储的内容不是Song
对象,所以它是字符串
因为您正在尝试调用getTitle
,我相信您希望为您的歌曲生成标题。所以,不妨尝试一下这样的方法:
Song song = (Song)thisSong;
song.getTitle();
for (int i=0, i < 4, i++){
String title = s + i; // no need to use Integer.toString() because using '+' with a String(s) turns i into a String too
Song mySong = new Song(title, artist, playTime, fileName);
System.out.print( mySong.getTitle() );
}
for(inti=0,i<4,i++){
String title=s+i;//不需要使用Integer.toString(),因为将“+”与字符串一起使用也会将i变成字符串
Song mySong=新歌(标题、艺术家、播放时间、文件名);
System.out.print(mySong.getTitle());
}
你想实现什么?请将歌曲
源代码添加到你的问题中。这首歌
是一个字符串
而不是歌曲
,因此方法undefined errorReference这首歌
的类型是对象
,它没有getTitle
方法。