I am using a system in my program in which there is one central "Manager" class that keeps track of the other classes and then other classes that handle various features of the program (called "Feature" classes). I have an abstract Manager class in a common library that implements several basic "Feature" classes. One of these feature classes needs a generic argument and other feature classes need to be able to access said generic argument.
This is not an issue when I am directly accessing a single instance of this generic argument. The issue occurs when I need to access a Set
of them.
Here is an example:
public abstract class AbstractManager<T extends User>{
private UserManager<T> userManager;
public UserManager<T> getUserManager(){
return userManager;
}
}
-
public class UserManager<T extends User>{
private HashMap<String, T> userMap;
public UserManager(){
userMap = new HashMap<>();
}
public T getUserEntry(String name){
return userMap.get(name);
}
public Set<Map.Entry<String, T>> getUserEntries(){
return userMap.entrySet();
}
}
-
public class AnotherFeatureClass{
private AbstractManager manager;
public AnotherFeatureClass(AbstractManager manager){
this.manager = manager;
}
public void doSomething(){
User user = manager.getUserManager().getUserEntry("username"); //this works fine
}
public void doSomethingElse(){ //this method does something to every user
//I would like something like this -- I don't imagine it is impossible since whatever T is it extends user
for(Set<Map.Entry<String, T>> entry : manager.getUserManager().getUserEntries()){
entry.getValue().doSomething();
}
//I'm using this right now -- it is very messy probably has many bugs that do who knows what and I can't help but assume there is a better way to do it
for(Object obj : manager.getUserManager().getUserEntries()){
try{
@SuppressWarnings("unchecked")
Set<Map.Entry<String, T>> entry = ((Set<Map.Entry<String, T>>) obj);
entry.getValue().doSomething();
}catch(ClassCastException e){
e.printStackTrace();
}
}
}
}