如何在客户端界面中实现类型安全?

时间:2019-02-07 22:58:30

标签: java api caching type-safety

我有一个缓存api,它使用数组作为缓存的存储。如何确保界面中的类型安全?我不太熟悉Java中的概念,因此,如果您可以提供详细的答案,我将不胜感激。

客户端API

公共类ClientCacheServiceImpl扩展了InternalCacheServiceImpl {

public ClientCacheServiceImpl(int sets, int entries, String algorithm) {
    super(sets, entries, algorithm);
}

内部API

公共类InternalCacheServiceImpl实现了InternalCacheService {

private final int numberOfSets;
private final int numberOfLines;

public final CacheElement[] cacheArray;
public final String algorithm;

public InternalCacheServiceImpl(int numberOfSets, int numberOfLines, String algorithm) {

}

public final Object get(Object key) {

}

公共接口InternalCacheService {

public Object get(final Object key);

public void  put(final Object key, final Object value);

public int size();

public void clear();

}

公共类CacheElement {

public int tag;
public Object data;
public boolean isEmpty;
public long timestamp;

}

1 个答案:

答案 0 :(得分:0)

您应该按如下所述引入通用参数类型T:

public interface InternalCacheService<T> {

      public T get(final T key);

      public void  put(final T key, final T value);

      public int size();

      public void clear();
    }

您为Integer类型的键实现类,值看起来像这样:

 public class InternalCacheServiceImpl implements InternalCacheService<Integer> {

    private final int numberOfSets;
    private final int numberOfLines;

    public final CacheElement[] cacheArray;
    public final String algorithm;

    public InternalCacheServiceImpl(int numberOfSets, int numberOfLines, String algorithm) {

    }

    public final Integer get(Object key) {
       //find the cached element by key and return it. Lets say it is the ith element
       return (Integer) cacheArray[i].data;
    }
}