简体   繁体   English

确定通用类型

[英]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. 我想出了另一种方法,它声明了getItemSize抽象。 So each loader can have it's own cache extended from base cache with desired getItemSize. 因此,每个加载器都可以从具有所需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. 如果您打算实现更多类,而不是反复检查instanceof ,则应使用具有getSize()方法或类似方法的包装器类。

public interface DataWrapper {

    public long getSize();

}

//...

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

// or even just
yourGeneric.getSize();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM