簡體   English   中英

Java和“類型安全…”

[英]Java and “Type Safety…”

我有一個關於類型安全的快速問題

我有這個方法和一個定義的類變量:

private List<SelectItem> listBait = null;


public List<SelectItem> getListBait() {
    // Cache to avoid resorting and rebuilding list numerous times
    if (null == listBait) {
        listBait = ConfigurationBean.getCurrentInstance().getMeta().getListBait();
    }
    return listBait;
}

現在,我在if中收到關於分配的警告。 它說Type safety: The expression of type List needs unchecked conversion to conform to List<SelectItem>

首先,ConfigurationBean中的getCurrentInstance方法是:

public static ConfigurationBean getCurrentInstance() {
    // This is a neat way to get a handle on the instance of this bean in the application scope from other Java code...
    FacesContext context = Util.getFacesContext();
    ConfigurationBean bean = (ConfigurationBean) context.getApplication().getVariableResolver().resolveVariable(context, "Configuration");
    return bean;
}

...,而getMeta方法(和實例變量)為:

private final MetaDataBean meta = new MetaDataBean();

public MetaDataBean getMeta() {
    return meta;
}

MetaDataBean中的getListBait()方法如下所示:

public List<SelectItem> getListBait() {
    List<SelectItem> options = new ArrayList<SelectItem>();
    for (Bait bait : getAllBaits()) {
        if (!bait.isInActive()) {
            options.add(new SelectItem(bait.getKey(), bait.getName()));
        }
    }
    return options;
}

因此,據我了解,它不應發出有問題的警告...? 任何可以向我解釋這一點的人-建議的解決方案似乎都不能解決問題(除了@SuppressWarning;-)。

這是在Java 1.6上。

提前致謝!

編輯
...並通過此編輯實際上解決了它!

發生的事情是,也許來自Eclipse的一些友好建議“幫助”我定義了MetaDataBean,如下所示:

public class MetaDataBean<whyFish> extends BaseBean implements Serializable {
:
:

...那是沒有道理的。 我不知道何時在聲明中添加了那個小“-”,但是刪除它會使所有警告消失:-)

非常感謝!! -現在,我仍然對到目前為止我所知道的Java有所信任;-)

/約翰

由於原始類型是該類型的擦除( 4.8 ),因此原始MetaDataBeangetListBait返回一個原始List

解決方案是從MetaDataBean刪除泛型類型參數,或者不使用原始類型,具體取決於該參數是否實際必要。

根據上次編輯。 泛型已被添加到一個類定義中-可能是由於Eclipse的友好幫助(很顯然,我接受了它卻並不確切知道自己做了什么!)。

有關進一步信息的出色注釋有助於找到錯誤的聲明:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM