Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java getConstructor(types) with parametised types

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!

like image 447
Mikesname Avatar asked Aug 23 '12 22:08

Mikesname


People also ask

Can constructor contain type parameter in Java?

Constructors are similar to methods and just like generic methods we can also have generic constructors in Java though the class is non-generic. Since the method does not have return type for generic constructors the type parameter should be placed after the public keyword and before its (class) name.

What is getConstructor in Java?

getConstructors() Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object. Annotation[] getDeclaredAnnotations()

Do generic classes need constructors?

A generic constructor is a constructor that has at least one parameter of a generic type. We'll see that generic constructors don't have to be in a generic class, and not all constructors in a generic class have to be generic.

Can you instantiate a generic class in Java?

Only reference types can be used to declare or instantiate a generic class. int is not a reference type, so it cannot be used to declare or instantiate a generic class.


2 Answers

At runtime, this:

  Map<String,Object>

Is actually just a Map, without any parameters.

Calling

 cls.getConstructor(Map.class) will be enough
like image 167
Eugene Avatar answered Nov 01 '22 20:11

Eugene


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

Constructor constructor = Foo.class.getConstructor(Map.class);
like image 31
John Ericksen Avatar answered Nov 01 '22 20:11

John Ericksen