简体   繁体   中英

Unchecked casting from superclass to generic T

Having recently started programming for android, i have run into a part of my code i wonder if can be designed in a better way. I have a SparseArray containing mapping of Int's representing resourceId's to an abstract class called Resource . My question arises when i want to retrieve my resource as multiple classes inherit from this class. Is there a better design for this solution than my current of trying to cast the Resource object to a generic T. This is indeed not that safe as any class can be used, not just the ones inherenting from Resource

public <T> T getAsset(int resourceId)
{
    try
    {
        T ReturnAsset = (T)resources.get(resourceId);
        return ReturnAsset;
    }
    catch(ClassCastException cce)
    {
        Log.w("Resource", "Invalid cast of asset "+cce.toString());
        return null;
    }
}

you could do this,

public <T extends Resource> T getAsset(int resourceId)
{
    try
    {
        T ReturnAsset = (T)resources.get(resourceId);
        return ReturnAsset;
    }
    catch(ClassCastException cce)
    {
        Log.w("Resource", "Invalid cast of asset "+cce.toString());
        return null;
    }
}

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