java需要编写一个通用函数,根据用户提供的输入,对地图中的对象进行类型转换
我的问题是,我将有一个映射,并希望编写一个通用方法,这样用户可以传递三个东西(映射、键名、ObjectType),我们将根据用户传递的内容获得类型转换后的值
这是我试过的伪代码。我能够实现其中的一部分
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));
}
}
在根据用户提供的输入进行打字后,我应该得到所有想要的对象
共 (0) 个答案