8

Is it possible to use getConstructor to obtain the constructor of the class X below?

public class A {
}

public class Y {

}

public class X extends Y {
    public X(A a, Y[] yy) {

    }
    public void someMethod() throws SecurityException, NoSuchMethodException {
        Class<? extends Y> clazz = X.class;
        Constructor<? extends Y> c =
            clazz.getConstructor(new Class[]{
                        A.class,
                        /* what do I put in here for the array of Ys? */
                    });
    }
}

Thanks

2 Answers 2

7

You can construct class literals involving array notation just like you would with "undecorated" classes, namely ClassName[].class. This literal yields "the class which describes arrays of instances of ClassName". In your case:

clazz.getConstructor(new Class[] {
    A.class,
    Y[].class
 });
Sign up to request clarification or add additional context in comments.

Comments

6

Or shorter.

    Constructor<X> c = X.class.getConstructor(A.class, Y[].class);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.