如何在一个对象中合并两个不同的对象类型?

时间:2021-03-10 12:19:54
callingmethod(){
File f=new File();  
//...
String s= new String();
//...

method( f + s);    // here is problem (most put f+s in object to send it to method)
}

cant change method args

不能改变方法args

method(Object o){
//...
//how to split it to file and String here 
}

for any thing not clear ask plz

对于任何不清楚的事情请问PLZ

2 个解决方案

#1


1  

You can e.g. put it in an array:

你可以,例如把它放在一个数组中:

method (new Object[] {f, s});

void method (Object o) {
    final Object[] arr = (Object[]) o;
    File f = (File) arr[0];
    String s = (String) arr[1];
}

#2


3  

The cleanest and most idiomatic way is to create a simple class to represent your pair:

最干净,最惯用的方法是创建一个简单的类来表示你的对:

static class FileString {
  public final File f;
  public final String s;
  FileString(File f, String s) { 
    this.f = f; this.s = s;
  }
}

then write

method(new FileString(file, string));

inside method:

FileString fs = (FileString)o;
// use fs.f and fs.s

Depending on further details, use a nested class like in my example, or put it into its own file. If you keep it close to the place where you instantiate it, then you can make the constructor private or package-private, like I did. But these are just the finer details.

根据更多细节,使用类似于我的示例中的嵌套类,或将其放入自己的文件中。如果你把它保持在你实例化的地方附近,那么你可以像我一样使构造函数成为私有或包私有。但这些只是更精细的细节。

#1


1  

You can e.g. put it in an array:

你可以,例如把它放在一个数组中:

method (new Object[] {f, s});

void method (Object o) {
    final Object[] arr = (Object[]) o;
    File f = (File) arr[0];
    String s = (String) arr[1];
}

#2


3  

The cleanest and most idiomatic way is to create a simple class to represent your pair:

最干净,最惯用的方法是创建一个简单的类来表示你的对:

static class FileString {
  public final File f;
  public final String s;
  FileString(File f, String s) { 
    this.f = f; this.s = s;
  }
}

then write

method(new FileString(file, string));

inside method:

FileString fs = (FileString)o;
// use fs.f and fs.s

Depending on further details, use a nested class like in my example, or put it into its own file. If you keep it close to the place where you instantiate it, then you can make the constructor private or package-private, like I did. But these are just the finer details.

根据更多细节,使用类似于我的示例中的嵌套类,或将其放入自己的文件中。如果你把它保持在你实例化的地方附近,那么你可以像我一样使构造函数成为私有或包私有。但这些只是更精细的细节。