mercredi 26 février 2020

Getting Constructor from Java Class that would be called for argument types, not requiring exact argument & parameter type match

Is there any way in Java (or in a Java library) to get the Constructor from a Class that would be called for the given arguments / argument types (not requiring exact argument & parameter type matches, instead including supertypes)?

i.e. I know about Class#getConstructor(Class<?>), but that only returns exact matches.

e.g., the following code throws a NoSuchMethodException, whereas I want to get the Constructor for A(CharSequence), as that's what would be called if I ran, e.g., A(""):

public class A {

    public A(Object o) {}
    public A(CharSequence cs) {}

    public static void main(String[] args) throws Exception {
        Constructor c = A.class.getConstructor(String.class);
        c.newInstance("");
    }
}

I imagine that such a method would also potentially throw an exception indicating that multiple constructors match, so it can't choose without the argument types being made more specific (like through explicit casts).

I'd also want to find this functionality for Methods.

Thanks.





Aucun commentaire:

Enregistrer un commentaire