I am trying to pass a variable number of arguments into a constructor, because not all of the values will always be required, and empty values are okay. Can I make it such that I can pass the variables in, in any order, and have them assign to their corresponding variables in the class correctly?
Few things to note in my case is that the variables in the class are Serialized; the values are either a String, an Integer, a boolean, or a Date; and the values passed into the constructor will always match their corresponding class values (If the value in the class is an Integer, an Integer will always be passed in for that value, not a String.parseInt(), for example)
Class Foo {
@SerializedName("id")
private Integer id;
@SerializeName("name")
private String name;
@SerializedName("isFoo")
private Date isFoo;
public Foo (Object... args){
}
}
In the constructor I want to be able to ask if whatever object name matches a variable in the class, to assign it to that variable. So if one of the Object's passed is an Integer named id, is there a way to match it to id? It should be able to be matched in a few cases:
Foo foo = new Foo(id, name) //In this case, the bool would be null
Foo foo2 = new Foo(name, id, isFoo) //Here the Integer is second, but should still be able to be passed in correctly
I think this can be solved via Reflection but I am not sure how. Any help would be amazing.
Aucun commentaire:
Enregistrer un commentaire