7

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

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

... how do I reference that parametized Map's class if I want to call:

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

(Where cls is the Foo class.)

I want to do something like:

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

... but that doesn't work.

I'm sure there's a simple answer to this!

2
  • 1
    Check out this link on Java "type erasure". See also Reflecting generic types. Commented Aug 23, 2012 at 22:41
  • Ah yes type erasure, had I thought more about this and actually read what Eclipse was trying to tell me I probably would have figured that out! Anyway, thanks for the link. Commented Aug 23, 2012 at 22:45

2 Answers 2

14

At runtime, this:

  Map<String,Object>

Is actually just a Map, without any parameters.

Calling

 cls.getConstructor(Map.class) will be enough
Sign up to request clarification or add additional context in comments.

Comments

4

You can reference the constructor by just the Map type. The generic parameters are erased for runtime:

Constructor constructor = Foo.class.getConstructor(Map.class);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.