Reputation: 634
I have the following method and I need to return two strings:
What is the best way to do it?
public static void getClassMetaData(List<Object> listClsObj) {
....
for (Field field : declaredFields) {
Class<?> type = field.getType();
System.out.println(type.getName());
System.out.println(field.getName());
}
}
Upvotes: 0
Views: 176
Reputation: 575
You should try and return a list as you are eventually using the attributes of field object in your other code.
Plus it would make the method more maintainable. The consumer of the method could decide what data it needs from the Field object.
Upvotes: 1
Reputation: 213311
I would rather return just the Field
, since you can get the type
and other information from the field
itself.
And then at the point of invocation, call the method - field.getType()
to get the type.
Seems like you are working with all the declared fields of your class, in which case you can just return the List<Field>
: -
public static List<Field> getClassMetaData(List<Object> listClsObj) {
// Rather than iterating over `declaredField`, just return it
return declaredFields;
}
Upvotes: 4
Reputation: 149
You can just return the Field instance instead of try to return 2 String. Otherwise, you can return a object containing your 2 String like a Pair object or a custom object.
class Pair<F, S> {
private final F first;
private final S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
// getter for first and second
}
Upvotes: 1
Reputation: 946
The more flexible and correct approach to return any number of elements - return List implementation of your data collection.
Upvotes: 2
Reputation: 3025
You can return an array of size 2 with both the fields.
return new String[]{type.getName(),field.getName()};
Upvotes: 1
Reputation: 136062
You can return a String array of course, but I think it would be better to simply return Field
Upvotes: 2