Reflection: how to find a constructor that accepts a list of objects?

I have a class that accepts a list in the constructor;

public class MyClass { private List<Structure> structures; public MyClass(List<Structure> structures) { this.structures = structures; } } 

what I need to create through reflection. How to define a .getConstructor () class call to find this?

Hello

+4
source share
2 answers

This should work:

 Constructor<MyClass> constructor = MyClass.class.getConstructor(List.class); 

or

 Constructor constructor = MyClass.class.getConstructor(new Class[]{List.class}); 

for Java 1.4.x or less

+7
source

You can find it by going through List.class . For instance:

 import java.util.*; import java.lang.reflect.*; public class Test { public static void main(String[] args) throws Exception { Class<?> clazz = MyClass.class; Constructor<?> ctor = clazz.getConstructor(List.class); ctor.newInstance(new Object[] { null }); } } 

If you need to check for common parameter types, you can use getGenericParameterTypes and examine the returned Type[] . For instance:

 Type[] types = ctor.getGenericParameterTypes(); System.out.println(types[0]); // Prints java.util.List<Structure> 

You do not need to specify a type argument when calling getConstructor , because you cannot overload the constructor using parameters with only different parameters. These types of parameters will have the same type of erasure. For example, if you try to add another constructor with this signature:

 public MyClass(List<String> structures) 

You will receive an error message:

MyClass.java:7: name clash: MyClass(java.util.List<java.lang.String>) and MyClass(java.util.List<Structure>) have the same erasure

+3
source

All Articles