简体   繁体   中英

How do I allow a parameter to be multiple types?

I am new to Java. I am sorry if this is a stupid question. I'd like to hand in a parameter that can either be a File or a string that I can then use to create a File. This is what I have so far:

public class DefaultOptions {

  public File setChooser(JFileChooser chooser, dir) {

  }

}


DefaultOptions dOptions = new DefaultOptions() {
  public File setChooser(chooser, dir) {
    if (!(dir instanceof java.io.File)) {
      String ds = dir.toString(); 
      File wd = new File(ds);
    } else {
      wd = (File) dir;
    }
    chooser.setCurrentDirectory(wd);
  }
}

What signature can I use for this line:

  public File setChooser(JFileChooser chooser, dir)         

If there is no way to do this, how can I simplify this?

Use Object :

public File setChooser(JFileChooser chooser, Object dir) {
    // ...
}

However, as pointed out in the comments, method overloading would probably definitely be better:

public File setChooser(JFileChooser chooser, String dir) {
     // handle String case
}

public File setChooser(JFileChooser chooser, File dir) {
     // handle File case
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM