简体   繁体   中英

Java generic container factory

I want to make a factory for cache containers, something like

public interface CacheMapFactory {
    public Map<K,V> createCacheMap(String tag, Class<K> kClass, Class<V> vClass);
}

with a possible simple implementation for testing

public class InMemoryCacheMapFactory implements CacheMapFactory {
    public Map<K,V> createCacheMap(String tag, Class<K> kClass, Class<V> vClass) {
        return new HashMap<K,V>();
    }
}

Other implementations might be, for example, based on Memcached or some other key-value storage.

Is it possible to convert the pseudocode above into something compileable with the desired semantics?

Your code would compile if you add another <K,V> to the methods:

public interface CacheMapFactory {
  public <K,V> Map<K,V> createCacheMap(String tag, Class<K> kClass, Class<V> vClass);
}

public class InMemoryCacheMapFactory implements CacheMapFactory {
  public <K,V> Map<K,V> createCacheMap(String tag, Class<K> kClass, Class<V> vClass) {
    return new HashMap<K,V>();
  }
}

I'm not sure what the tag would do, but I guess that's part of the further implementation.

Additionally, you could rely on type inference like this:

public interface CacheMapFactory {
  public <K,V> Map<K,V> createCacheMap(String tag );
}

public class InMemoryCacheMapFactory implements CacheMapFactory {
  public <K,V> Map<K,V> createCacheMap(String tag ) {
    return new HashMap<K,V>();
  }
}

public class Test {
  public void test() {
    CacheMapFactory f = new InMemoryCacheMapFactory();
    Map<String, Long> m = f.createCacheMap( "mytag" ); //K and V are inferred from the assignment
  }
}

If you just want it to compile then you can just do this:

public interface CacheMapFactory {
    public <K, V> Map<K,V> createCacheMap(String tag, Class<K> kClass, Class<V> vClass);
}

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