I have a situation where I'd like to allow a user to complete a form, where the input data is a list of either String values or Boolean values. This is very much like the Settings list on any mobile phone, a series of String values and toggles.
So, I have a Field
object defined as such:
public class Field<T> {
private T value;
...
private T getValue() {
return value;
}
}
The problem is when I go to display these in a RecyclerView
or just grab the values from a Map
, there is no safe way to know what type the value is, String or Boolean.
Because of this, I end up with a lot of (String)field.getValue()
and ((Field<String>)field).setValue("someString")
. Is there any way to avoid casting entirely? I am totally open to changing my design approach to this Field
object, I just want it to be clean.
I have contemplated having methods like getStringValue()
and getBooleanValue()
so that the caller knows it's getting either a String or Boolean at runtime, but this would result in each field having one method that returns a valid object, while the others return null. I want the caller to not have to know what it's getting back.
Thanks for your help!
Update
Here's an example of how I would access the fields from a LinkedHashMap and create a Person
object with them:
// Create the map in one place
LinkedHashMap<String, Field> fields = new LinkedHashMap<(PERSON_FIELDS_NUM);
fields.put(Constants.Field.FIRST_NAME_KEY, new Field(Constants.Field.FIRST_NAME_KEY, "First Name", "Tap to enter"));
fields.put(Constants.Field.LAST_NAME_KEY, new Field(Constants.Field.LAST_NAME_KEY, "Last Name", "Tap to enter"));
// ...Grab fields in another
Person person = new Person();
Field firstName = this.fields.get(Constants.Field.FIRST_NAME_KEY);
Field lastName = this.fields.get(Constants.Field.LAST_NAME_KEY);
person.setFirstName((String)firstName.getValue());
person.setLastName((String)lastName.getValue());