在不创建类的新实例的情况下更改“File”参数的值

时间:2011-12-07 01:07:16

标签: java file object parameters

我这里有点问题。

我在这些方法中声明了一个新的对象“Fleet”:

public void run() throws FileNotFoundException
{
    File file = new File(getFile());
    Fleet fleet = new Fleet(file);
    buildFleet(file, fleet);
    }

private void buildFleet(File file, Fleet fleet) throws FileNotFoundException
{
    fleet.addVehicle(Honda);
    userMenu(fleet);

}

最后一行调用userMenu()方法。在这个方法中,我需要能够在Fleet内部更改“File”的值,而无需创建类的新实例。

private void userMenu(Fleet fleet) throws FileNotFoundException
{
    PrintWriter pw = new PrintWriter("temp.txt");
    File file = new File("temp.txt");
    fleet = new Fleet(file);

    this.createMenu();
    choice = this.menu.getChoice();


while(choice != 8)
{
    switch(choice)
    {
    case 1:
        //Do stuff
        fleet.addVehicle(Honda);
        break;
    }
}

另外,我不允许创建任何新的类级数据。 有什么建议吗?

2 个答案:

答案 0 :(得分:1)

文件的Fleet类的setter怎么样:

public class Fleet {
   private File file;
   ...

   public void setFile( File file ){
     this.file = file;
   }
}

然后,您可以通过调用

调用此方法来更改车队对象内的文件
fleet.setFile( myNewFile );

答案 1 :(得分:0)

解决:

我改变了:

private void userMenu() throws FileNotFoundException
{
    PrintWriter pw = new PrintWriter("temp.txt");
    File file = new File("temp.txt");

为:

private void userMenu(Fleet fleet) throws FileNotFoundException
{
    PrintWriter pw = new PrintWriter("temp.txt");
    File file = new File("temp.txt");
    fleet.file = file;