开发者

How to 'getConstructor' where constructor signature contains java array

开发者 https://www.devze.com 2022-12-16 11:35 出处:网络
Is it possible to use getConstructor to obtain the constructor of the class X below? public class A { }

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

public class A {
}

public开发者_StackOverflow社区 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


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
 });


Or shorter.

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

精彩评论

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

关注公众号