简体   繁体   English

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

[英]How to merge two different object type in one object?

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 无法更改方法参数

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

for any thing not clear ask plz 对于任何不清楚的事情请问plz

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. 但是,这些只是更好的细节。

You can eg 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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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