2 Replies Latest reply on Oct 28, 2010 2:04 PM by jtahlborn

    Generics and polymorphism: writing database-backed collections api

      or; is there any way to tell what type a generic has been instantiated with? e.g., for an ArrayList to know that it was constructed as ArrayList<String> rather than ArrayList<Integer>?

      I'm trying to write a wrapper/adapter layer to make a disk-backed Map<K,V> type using tokyocabinet as the disk storage technique.

      Tokyocabinet is a tuple store that I'm using through a JNI. It behaves essentially like a map (put, get, iterate over keys, etc) except it only accepts two key types (String and byte[]) and likewise two value types (String and byte[]) accordingly -- so you can put(String,String) or put(byte[],byte[]) but not put(String,byte[]). A huge pain. But wicked fast compared to everything else we've tried.

      So in order to hide all the ugly behind something that behaves like a regular old java collections Map, what I want to write is something like this:
      public class TokyoMap<K,V> implements Map<K,V> {
        public V put(K key, V val) { 
          // and then do put(String,String) 
          // or serialize the objects to byte[] and do put(byte[],byte[]),
          // depending on the instanceof of key and value.  Kinda gross.
      At put- and get- time I can use instanceof to determine what types to write to the database, and that sorta works. But for iterating over entries (ie via entrySet().iterator() ) tokyocabinet assumes I know what keys I've been putting in the database -- it offers nextkey():String and nextkey2():byte[], which is kindof awful... and at iteration time there's no user-provided object I can check instanceof on to decide which to use. I could set a flag the first time put() or get() is called, I suppose, but I'm fishing for something a little less ham-handed, if such a thing exists.

      Is there a way for my code to access the current bindings of K and V? alternately, I'm only using a few types of mappings; I wouldn't mind writing an implementation for each of them, if their usage were a matter of the user creating a TokyoMap<String,Integer> and automagically being delivered of the appropriate impl.