Java getConstructor (types) with parameterized types

If I have a class with a constructor that takes a parameterized generic type:

public class Foo {
    public Foo(Map<String, Object> data) {
      ...
    }
}

... how can I refer to this parameterized Map class if I want to call:

Constructor constructor = cls.getConstructor(/*the Map class! */)

(Where clsis the Foo class.)

I want to do something like:

Constructor constructor = cls.getConstructor(Map<String,Object>.class);

... but it does not work.

I am sure there is a simple answer to this question!

+5
source share
2 answers

At runtime, this is:

  Map<String,Object>

This is actually just a map, without any parameters.

Call

 cls.getConstructor(Map.class) will be enough
+12
source

You can only refer to a constructor by map type. General parameters are erased at runtime:

Constructor constructor = Foo.class.getConstructor(Map.class);
+4
source

All Articles