0

For instance, I can have

Class c = Map.class;

But what if I need c to refer to the class Map<String, ValueClass>?

I want to do something which expresses

Class c = (Map<String, ValueClass>).class;

My use case is that I need to do this so that I can pass c to getConstructor

Peeyush Kushwaha
  • 3,453
  • 8
  • 35
  • 69
  • if I understand it correctly , you should look at this: [a get-type-of-a-generic-parameter-in-java-with-reflection](https://stackoverflow.com/questions/1901164/get-type-of-a-generic-parameter-in-java-with-reflection) – developer-guy May 18 '18 at 13:38

2 Answers2

1

The spcecific type Map<String, ValueClass> share the same class object with Map, so you can not aquire a custom class object.

At run time, (Map<String, ValueClass>).class equals Map.class because of type erasure:

public static void main(String[] args) {
    Map map = new HashMap();
    Map<String, Integer> anotherMap = new HashMap<>();
    System.out.println(map.getClass().equals(anotherMap.getClass())); // true
}
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • This explains why what I proposed won't work, but the question of how to get a reference to generic classes with specific type parameters still stands. Unless it can't be done at all, in which case something's broken because that's what `getConstructor` method expects – Peeyush Kushwaha May 18 '18 at 13:29
  • Well, then update answer to reflect that claim and I'll accept it if no one disagrees. Then I guess how to deal with `getConstructor` becomes a different question – Peeyush Kushwaha May 18 '18 at 13:31
1

If you really want to get the static type as you require, you can force your way to it using casts (albeit through raw types):

Class<Map<String, Object>> cl = (Class) Map.class;

However, as pointed in other comments and other answer, that doesn't help you as, at runtime, your class.getConstructor() call will only see Map.class anyway.
Just consider the signature of getConstructor:

getConstructor(Class<?>... parameterTypes)

The implementation retrieves the constructor by comparing parameters (check the source of java.lang.Class.arrayContentsEq(Object[], Object[])).
To summarize, it boils down to comparing (Class) cl == Map.class, and that returns true at runtime, which explains why it's no use looking for the generic class instance.


The value of Class<Map<String, Object>> cl would only be effectual if that were used for static type checking, but in this case, it doesn't help.

ernest_k
  • 44,416
  • 5
  • 53
  • 99