开发者

Reflection: How to find a constructor that takes a list of objects?

I have a class that takes a List in the constructor;

public class MyClass {

       private List<Structure> structures;

       public MyClass(List<Structure&g开发者_如何学Got; structures) {
          this.structures = structures;
       }
}

that I need to instantiate via reflection. How do I define the call to class.getConstructor() to find this?

Regards


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


You can find it just by passing in List.class. For example:

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 validate the generic parameter types, you can use getGenericParameterTypes and examine the Type[] which it returns. For example:

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

You don't need to specify the type argument when you call getConstructor because you can't overload the constructor by using parameters with just different type parameters. Those parameter types would have the same type erasure. For example, if you try to add another constructor with this signature:

public MyClass(List<String> structures)

you'll get an error like this:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜