How to avoid having to use @SuppressWarnings(“unchecked”)?

时光毁灭记忆、已成空白 提交于 2019-12-06 08:53:32

and I'm wondering if there's a 'better' way to do what I'm doing here (for instance, somehow storing a Type when I write the cache, and reading this value to be able to instantiate a specific type?)

Use generics here. If you have

public <String, P extends Serializable> R get( String key);
public <String, P extends Serializable> void put( String key, R value);

I am not pointing to already existing Cache implementations. Like Guava, those support cache anyways, but I blieve you want to improve this code.

At the last resort, One big thing is to always keep @SupressWarnings as close as possible to the code causing it.

Assuming that both key and value are Serializable you could use these signatures

public <R extends Serializable, P extends Serializable> R get( P key);
public <R extends Serializable, P extends Serializable> void put( P key, R value);

Wherever you have like this

// Cast required here, and this row generates unchecked warning
summary = (MyObject) Cache.get(getCacheKey());

It will generates unchecked warning, to avoid this better option to make CollectionHelper class and generates unchecked warning in your CollectionHelper class. And use the CollectionHelper class to return the objects from that class.

For example,

public class CollectionsHelper {
    /**
     * 
     * @param list
     *            of List type
     * @return list - List of MyObject type
     */
    @SuppressWarnings("unchecked")
    public static List<MyObject> getMyObjects(List list) {
        return (List<MyObject>) list;
    }
}

and use it in this way

List<MyObject> objList = CollectionsHelper.getMyObjects(Cache.get(getCacheKey());

You don't need to add @SupressWarnings in your service or implementation class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!