1

Working in Java 1.8, I need to determine the class of K and V in HashMap. My first attempt has not worked, and I admit I have no idea where to go from here. I am hoping to feed this

public static int foo(Object obj){
    int result = 0;
    String x = obj.getClass().getSimpleName();

    switch(x){
        case "HashMap":
            Type sooper = obj.getClass().getGenericSuperclass();
            Type key = ((ParameterizedType)sooper).getActualTypeArguments()[ 0 ];
            Type value = ((ParameterizedType)sooper).getActualTypeArguments()[ 1 ];
            System.out.println(sooper.getTypeName());
            System.out.println(key.getTypeName());
            System.out.println(value.getTypeName());

            break;
      }
}

public static void main(String[] args) {
    foo(new HashMap<Integer,Character>());
}

Output:

Class ::    HashMap
java.util.AbstractMap<K, V>
K
V
BAMF4bacon
  • 523
  • 1
  • 7
  • 21
  • Have you look at: https://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime ? – Jorn Vernee Jun 01 '17 at 12:10
  • Thanks for link. Unless I am mistaken, this works when you know the declared class. I can't do something like GenericClass(new HashMap). That would tell me it is a HashMap, and I am back to the original problem. – BAMF4bacon Jun 01 '17 at 12:27
  • One other option is to get some elements from the map and call `getClass` on those, but there is no guarantee that those are of the exact types `K` and `V` (could be a subtype). Otherwise it's not possible. – Jorn Vernee Jun 01 '17 at 12:30

2 Answers2

0

Typically you will not be able to retrieve the types of K and V due to type erasure. After you've created the template object, the system doesn't see it as <unique_type K, unique_type V> but rather <Object K, Object V>

I did some looking and found another question here on SO that offers an ugly, but working solution to the problem.

Llebac
  • 1
  • 2
0

I solved this on my own by using an Enum type and passing this as an argument to my function, because the function caller knew the class in this case.

BAMF4bacon
  • 523
  • 1
  • 7
  • 21