I am trying to create an object holder util class to be short. Forexample;
public ResponseAbc bringMeStuff(RequestAbc request){
ResponseAbc response = new ResponseAbc();
/* Setting request here.. */
response = bringMeLotsOfStuff(request);
/* Here I am calling the Util class */
Util.putToObjectHolder("myAbcResponse", response);
return response;
}
public void testMe(){
/* Testing objectHolder */
ResponseAbc newResponse = (ResponseAbc) Util.getFromObjectHolder("response");
}
Here is the Util class
public class Util<T> {
private static Util<?> instance = null;
private Map<String, T> objHolder;
private Util() {
}
/* I strongly think Util class should be singleton if I want to hold the map globally */
public static Util<?> getInstance() {
if (instance == null) {
instance = new Util();
}
return instance;
}
public static <T> void putToObjectHolder(String objectName, T objectType) {
// Map<String, T> holder = (Map<String, T>) getInstance().getObjHolder();
// holder.put(objectName, objectType);
getInstance().getObjHolder().put(objectName, objectType); //-> Argument error
}
public static <T> Object getFromObjectHolder(final String objectName) {
Map<String, T> holder = (Map<String, T>) getInstance().getObjHolder();
T obj = null;
for (Entry<String, T> entry : holder.entrySet()) {
if (entry.getKey().equals(objectName)) {
obj = entry.getValue();
} else {
obj = null;
}
}
return obj;
}
public Map<String, T> getObjHolder() {
if (objHolder == null) {
objHolder = new HashMap<String, T>();
}
return objHolder;
}
public void setObjHolder(Map<String, T> objHolder) {
this.objHolder = objHolder;
}
}
If I uncomment putToObjectHolder method, it works but I am not pretty sure it supposed to work that way. I mean creating an other map and assigning to it should do the trick.
What I intent to do is holding a static Map holder with single instance so I can put whatever object I want with a name and get that object whenever I want if it exist in that 'global holder'.
PS: It is pretty messy with type safety warnings for sure, I would love to improve that aswell though I am not sure how to.
Thanks in advance.