简体   繁体   中英

Are generic methods required to have a generic type parameter to work correctly?

I'm just going over some classes trying to generify the code to modernise it somewhat, and I've noticed that there is a library method that is used quite commonly in my classes that seems to be fundamentally wrong, but I don't feel I have the knowledge to quite explain whether it is actually wrong or not.

We use ListModel's from a Java Web UI Framework called ZK for our data retrieved from database tables and then shown in Listboxes, and I noticed there is a lot of code that does something along the lines of:

ListModelList lm = (ListModelList) lbox.getListModel();
lm.add(item);

The library method declaration for "getListModel()" is:

public <T> ListModel<T> getListModel()

and can be found here: http://www.zkoss.org/javadoc/latest/zk/org/zkoss/zul/Listbox.html#getListModel()

Now when I put do this:

ListModelList<Material> lm = new ListModelList<Material>(itemList);
lbox.setModel(lm);

ListModelList model = (ListModelList) lbox.getListModel(); // returned type is ListModel<Object> and generates a compiler warning

Generates a compiler warning due to cast from ListModel due to type erasure.

But if I do this:

ListModelList<Material> lm = new ListModelList<Material>(itemList);
lbox.setModel(lm);

ListModelList<Material> model = lbox.getListModel(); // compiler error.

Am I incorrect in thinking that this is an API flaw and requires everyone to do a unsafe cast to the correct generic type (if you even know it) to use generics? Or is there a better way prevent the seemingly needless cast every time?

getListModel() returns a ListModel<T> and not a ListModelList<T> . So you can replace ListModelList<Material> with ListModel<Material> , or if you need the methods of ListModelList and are sure that this is the type of the object returned, you must do an explicit cast.

ListModel<Material> model = lbox.getListModel(); 

or

ListModelList<Material> model = (ListModelList<Material>)lbox.getListModel(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM