[英]How do you create a constructor that takes an array of “Range” objects and initializes the list, list is intialized to an ArrayList
[英]Reflection: How to find a constructor that takes a list of objects?
我有一个 class 在构造函数中采用 List ;
public class MyClass {
private List<Structure> structures;
public MyClass(List<Structure> structures) {
this.structures = structures;
}
}
我需要通过反射来实例化。 如何定义对 class.getConstructor() 的调用以找到它?
问候
这应该有效:
Constructor<MyClass> constructor = MyClass.class.getConstructor(List.class);
或者
Constructor constructor = MyClass.class.getConstructor(new Class[]{List.class});
对于 Java 1.4.x 或更低
您只需传入List.class
即可找到它。 例如:
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 });
}
}
如果需要验证泛型参数类型,可以使用getGenericParameterTypes
并检查它返回的Type[]
。 例如:
Type[] types = ctor.getGenericParameterTypes();
System.out.println(types[0]); // Prints java.util.List<Structure>
调用getConstructor
时不需要指定类型参数,因为不能通过使用仅具有不同类型参数的参数来重载构造函数。 这些参数类型将具有相同的类型 erasure 。 例如,如果您尝试使用此签名添加另一个构造函数:
public MyClass(List<String> structures)
你会得到这样的错误:
MyClass.java:7:名称冲突:
MyClass(java.util.List<java.lang.String>)
和MyClass(java.util.List<Structure>)
具有相同的擦除
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.