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!
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.
getConstructors() Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object. Annotation[] getDeclaredAnnotations()
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.
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.
At runtime, this:
Map<String,Object>
Is actually just a Map, without any parameters.
Calling
cls.getConstructor(Map.class) will be enough
You can reference the constructor by just the Map type. The generic parameters are erased for runtime:
Constructor constructor = Foo.class.getConstructor(Map.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With