My problem Statement is that i will have a Map and want to write a generic method such that user can pass three thing(Map,Keyname,ObjectType) and we will be getting the Object that is value after type-casting based on what user pass
This is the dummy code which i tried. I am able to achieve part of it
public class Convert {
public static void main(String args[]) {
School school = new School();
school.setName("sa");
Student st = new Student();
st.setName("asni");
school.getStudentSet().add(st);
Map<String,Object> am = new HashMap<>();
am.put("St",st ); // value is Student Object
am.put("S",school.getStudent()); // value is Set<Student>
am.put("school", school); // value is School Object
Student s = getvalue(am,"St",Student.class);//this is working
School sd = getvalue(am,"school",School.class);//this is working
Student st1 = new Student();
st1.setName("aaa");
getvalue(am,"S",Set.class).add(school); //in this school object is getting add which should not happen
System.out.println();
}
public static <T> T getvalue(Map<String,Object> am,String name, Class<T> rtype) {
return rtype.cast(am.get(name));
}
}
I should be getting all the desired object after getting typecasted based on the input provided by the user