lundi 23 mars 2015

How to get constructor by inexact type of parameters?

I need to find a constructor, which can accept both class and it's superclass.


The get method does not work, causing NoSuchMethodException:



package tests.java;

import java.lang.reflect.Constructor;

public class Try_ConstructorReflection {

public static class A {

}

public static class A1 extends A {

}

public static class A2 extends A {

}

public static class B {
public B(A a) {
}
}

public static class B1 {
public B1(A1 a) {
}
}

public static class B2 {
public B2(A2 a) {
}
}

public static void main(String[] args) throws NoSuchMethodException, SecurityException {

Class<?> cls = B.class;

Constructor<?> cons = cls.getConstructor(B1.class);

System.out.println(cons.toString());

}

}


Is the only way to accomplish the task is to enumerate all constructor manually with getConstructors() ?






Aucun commentaire:

Enregistrer un commentaire