I am trying to create a generic container to which I can pass any data and extract it later with the compiler keeping track of the classes.
Example:
Container a = new Container(0.3);
a.getValue();// returns 0.3 of type double
Container b = new Container("OMG");
b.getValue();// returns "OMG" of type StringI have no restrictions on how to do it. I was thinking of something like this.
public class GameSetting { Object value; Class valueClass; public GameSetting(Object value, Class valueClass) { this.value = value; this.valueClass = valueClass; } public Class<?> getValue() { return (valueClass)value; } public Class getClass(){return this.valueClass;}
}but I get unknown class:'valueClass' error.
Please help
Thank you
22 Answers
You need to look into Java Generics. Your basic container class will look something like this...
public class Container<T> { private final T value; public Container(T value) { this.value = value; } public T getValue() { return value; }
}You then use it like this...
Container<Double> a = new Container<>(0.3);
a.getValue();// returns 0.3 of type double
Container<String> b = new Container<>("OMG");
b.getValue();One thing to beware of with generics is that they don't work directly with Java primitive types - so if you're going to use them with int and double you need to understand Java's autoboxing feature.
public Class<?> getValue() { return (Class) (value); }You are trying to type cast with the references instead of Class. Also you shouldn't override the final method getClass().