简体   繁体   中英

Determine Generic Type

I'm writing a generic cache that can hold bitmaps and strings for now so I can use it in different loaders.

public class Cache<T> {}

At some point I have to calculate the size of object:

private long getSize(T t)
{
    if (t == null) return 0;
    if (t instanceof Bitmap) return ((Bitmap)t).getRowBytes() * ((Bitmap)t).getHeight();
    if (t instanceof String) return ((String)t).getBytes().length;
    return 0;
}

This is how I did it for now. I want to know if this is correct and if there is any better way like polymorphic type determining to do this?

--- EDIT ---------------------------------------

I figured out another way and it's declaring getItemSize abstract. So each loader can have it's own cache extended from base cache with desired getItemSize.

class BitmapCache extends Cache<Bitmap>
{
    @Override
    public long getSize(Bitmap bitmap)
    {
        if (bitmap == null) return 0;
        return bitmap.getRowBytes() * bitmap.getHeight();
    }
}

If you're planning on implementing even more classes, rather than repeatedly checking instanceof , you should use a wrapper class that has a getSize() method, or it's likeness.

public interface DataWrapper {

    public long getSize();

}

//...

private <T extends DataWrapper> long getSize(T t) {
    return t.getSize();
}

// or even just
yourGeneric.getSize();

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