java声明泛型类,Java泛型:声明泛型类型的映射值

I am new to generics.

Having a Map like

private static Map map;

and a method like

public T getObject(final Class myClass) {

return (T)map.get(myClass);

}

How to change the map declaration in order to not have to do the cast when returning from the method ?

解决方案

You would need to make a generic class, not a generic method:

public class MyClass {

private Map map;

public T getObject(final String key) {

return map.get(key);

}

}

Also, I changed the parameter from a Class to a String. It doesn't make sense to pass a Class if map.get() expects a String.

Edit: I didn't notice that map was static. If you can change it to non-static without it breaking other parts of your program, this could work. If you can't, then you cannot avoid a cast.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值