簡體   English   中英

Eclipse警告:類型安全(Java Generics)

[英]Eclipse warning: Type safety (Java Generics)

我有以下Hibernate代碼:

List<Book> result;    

result = hibernateTemplate.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createQuery("SELECT DISTINCT b FROM Book as b LEFT JOIN FETCH b.authors");

            List list = query.list();

            return list;
        }
    });

我從hibernateTemplate.execute(...開始收到以下警告hibernateTemplate.execute(...

Multiple markers at this line
    - HibernateCallback is a raw type. References to generic type HibernateCallback<T> should be parameterized
    - Type safety: The expression of type new HibernateCallback(){} needs unchecked conversion to conform to HibernateCallback<Object>
    - Type safety: Unchecked invocation execute(new HibernateCallback(){}) of the generic method execute(HibernateCallback<T>) of type 
     HibernateTemplate
    - Type safety: The expression of type new HibernateCallback(){} needs unchecked conversion to conform to HibernateCallback<List<Book>>
    - Type safety: The expression of type List needs unchecked conversion to conform to List<Book>

所以這真的很難。

你能解釋一下嗎?

  1. 編譯器看到了什么與預期的一致,為什么?

  2. 修復這些警告最安全的方法是什么...即不是@SuppressWarnings("unchecked")

我已經嘗試過以下鏈接中出現的提案: https//forums.oracle.com/forums/thread.jspa?threadID = 1182661 (頁面底部出現的三個建議中的第二個建議)....但它不起作用。

謝謝!

PS我知道如何解決我應該得到的其他警告,因為List list = query.list(); 這就是為什么我在我的問題中沒有提到它。

PS-2根據Eclipse,該方法的簽名是<Object> Object org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateCallback<Object> action) throws DataAccessException

該類的簽名是HibernateCallback<T>並定義了一個方法T doInHibernate(Session)但你沒有提供類型參數T - 這就是編譯器所抱怨的:它不確定你的代碼是否真的產生了在適合您的result變量的List<Book>中。

你是正確的,添加@SuppressWarnings不是一個好主意(它不會增加實際的類型安全性),請嘗試這樣做:

List<Book> result = hibernateTemplate.execute(new HibernateCallback<List<Book>>() {
    public List<Book> doInHibernate(Session session) throws HibernateException, SQLException {
        Query query = session.createQuery("SELECT DISTINCT b FROM Book as b LEFT JOIN FETCH b.authors");

        List list = query.list();

        return list;
    }
});

這會將類型參數T設置為List<Book>預期結果類型,特別是這意味着:

  • new HibernateCallback<List<Book>>()而不僅僅是new HibernateCallback()
  • 這就要求public Object doInHibernate(Session ...成為public List<Book> doInHibernate(Session ...

這仍然留下了未參數化的List list = query.list(); 您可以使用Hibernate HQL結果中的“ 如何避免類型安全警告”中描述的方法之一處理 (我個人更喜歡那里提到的演員助手方法)。

這不只是......

new HibernateCallback<List>()...

這可能意味着方法返回類型將是List而不是Object。 雖然那時你還需要指定List類型嗎?

暫無
暫無

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

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