mercredi 28 janvier 2015

Generic parameter determining instance field type at execution

Explanation of the situation:


I want to instanciate an object that can that have basically 2 parameters. A set of 'meta-parameters' and a value. The type of the value is determined by the 'meta-parameters'.


Example (simplified):



public class Meta
{
private Class<?> type;

public Meta(Class<?> type)
{
this.type = type;
}

public Class<?> getType()
{
return this.type;
}
}

public class Record
{
private # value;

public Record(Meta meta, # value)
{
//Initialization
}
}


Expected usage:



Meta metaString = new Meta(String.class);
Record recordString = new Record(metaString, "hello");
Meta metaDouble = new Meta(Double.class);
Record recordDouble = new Record(metaDouble, 12.8);


My doubt yet is how to determine the type of 'value' (actually symbolized by '#'). I think generics or reflexion could solve my problem but I can't figure out how a parameter in the constructor can influence the type of another parameter.


Can anyone has an idea how to solve that ?


Note: it is also acceptable for me to initialize the record value later with a setter.






Aucun commentaire:

Enregistrer un commentaire