public class Bean2Map {
public static HashMap format(TbAccount in){
HashMap map=new HashMap();
map.put(MyKey.TBACCOUNT.NAME, in.getName());
map.put(MyKey.TBACCOUNT.ACCOUNT, in.getAccount());
map.put(MyKey.TBACCOUNT.PASSWORD, in.getPassword());
map.put(MyKey.TBACCOUNT.SEX, in.getSex());
return map;
}
public static HashMap format(TbDish in){
HashMap map=new HashMap();
map.put(MyKey.TBDISH.NAME, in.getName());
map.put(MyKey.TBDISH.KIND, in.getKind().getName());
map.put(MyKey.TBDISH.PRICE, in.getPrice()+"");
map.put(MyKey.TBDISH.ID, in.getDishId().toString());
return map;
}
public static HashMap format(TbRestaurant in){
HashMap map=new HashMap();
map.put(MyKey.TBRESTAURANT.ID, in.getRestaurantId().toString());
return map;
}
public static HashMap format(Object in){
HashMap map=new HashMap();
map.put("ob", "ob");
return map;
}
public static List<HashMap> formatDishList(List<TbDish> in){
List<HashMap> list=new ArrayList<HashMap>();
for (TbDish dish : in) {
list.add(format(dish));
}
return list;
}
public static <T> List<HashMap> format(List<T> in){
List<HashMap> list=new ArrayList<HashMap>();
for (T item : in) {
list.add(format(item));
}
return list;
}
}当我用format(list),(list是List<TbRestaurant>类型)为什么for循环里面调用的是format(Object in)而不是format(TbRestaurant in)啊 求指教啊!!
public static HashMap format(TbAccount in){
HashMap map=new HashMap();
map.put(MyKey.TBACCOUNT.NAME, in.getName());
map.put(MyKey.TBACCOUNT.ACCOUNT, in.getAccount());
map.put(MyKey.TBACCOUNT.PASSWORD, in.getPassword());
map.put(MyKey.TBACCOUNT.SEX, in.getSex());
return map;
}
public static HashMap format(TbDish in){
HashMap map=new HashMap();
map.put(MyKey.TBDISH.NAME, in.getName());
map.put(MyKey.TBDISH.KIND, in.getKind().getName());
map.put(MyKey.TBDISH.PRICE, in.getPrice()+"");
map.put(MyKey.TBDISH.ID, in.getDishId().toString());
return map;
}
public static HashMap format(TbRestaurant in){
HashMap map=new HashMap();
map.put(MyKey.TBRESTAURANT.ID, in.getRestaurantId().toString());
return map;
}
public static HashMap format(Object in){
HashMap map=new HashMap();
map.put("ob", "ob");
return map;
}
public static List<HashMap> formatDishList(List<TbDish> in){
List<HashMap> list=new ArrayList<HashMap>();
for (TbDish dish : in) {
list.add(format(dish));
}
return list;
}
public static <T> List<HashMap> format(List<T> in){
List<HashMap> list=new ArrayList<HashMap>();
for (T item : in) {
list.add(format(item));
}
return list;
}
}当我用format(list),(list是List<TbRestaurant>类型)为什么for循环里面调用的是format(Object in)而不是format(TbRestaurant in)啊 求指教啊!!
也就是说编译的时候T被擦除,取而代之的是Object(即在.class文件中没有T的信息,只有Object信息)
所以
for (T item : in) 被编译为 for (Objec item : in) --.class文件的伪代码被编译为这样的信息
而编译期不知道用户会传入什么样的T,所以不可能编译为 for (TbRestaurant item : in)
所以item就是Object类型而不是TbRestauant类型,所以就会调用参数为Object的format方法
那有没有其他方法让for循环里的format重载正确的对应类型的方法呢?
只能在循环中自己判断
比如
for (T item : in) {
if (item intanceof xxx) {format((xxx)item);} //只能强行转换为相应的类型
else format(item);
}