Need help with an odd Java method signature -- reflection?

Status
Not open for further replies.

TheDan666

Ars Tribunus Militum
2,359
I've got an odd issue that I was hoping the Hive Mind might shed some light on. I'm working with Morphia which is the Java MongoDB API. When peforming a query, there is a method called .retrievedFields() that will restrict the amount of columns that are returned to a list of string specified in the call. It is defined in their API like this:

Code:
Query<T> retrievedFields(boolean include,
                         String... fields)
The boolean include means whether you want to include or exclude the list of columns. So given this example, I can restrict the columns returned to just foo and bar:

Code:
String field1 = "foo";
String field2 = "bar";

query.retrievedFields(true,field1,field2);

The issue I have is that I want to call this method with a dynamic amount of strings representing columns. It could be 1,2,x. So given the following:
Code:
List<String> fields = new ArrayList();
fields.add("foo";
fields.add("bar";
fields.add("cow";

How can I call this retrievedFields method and have it just put in a dynamic amount of String objects at runtime? I don't if I've ever seen a method that accepts an arbitrary amount of String objects. I've tried concatenating the strings and it doesn't work. I can daisychain .retriedFields() calls to same original method but doing that it only listens to the last method call.

Any help would be greatly appreciated!

Thanks,
The Dan
 
Because arrays are crufty, I tend to make vararg methods delegate to overloaded collection methods like:
Code:
Query<T> retrievedFields(boolean include, String... fields) {
  return retrievedFields(include, Arrays.asList(fields));
}

Query<T> retrievedFields(boolean include, Collection<String> fields) {
  // actual implementation goes here
}
Then you can pass th list directly into the latter method.
 
Status
Not open for further replies.