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

XDR :

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.

Holger :

You can use java.beans.Expression.

To demonstrate the behavior:

public class A {
    public A(Appendable o) { System.out.println("A(Appendable)");}
    public A(CharSequence cs) { System.out.println("A(CharSequence)");}

    public static void main(String[] args) throws Exception {
        // calls A(CharSequence)
        A a1 = (A)new Expression(A.class, "new", new Object[]{ "string" }).getValue();
        // calls A(Appendable)
        A a2 = (A)new Expression(A.class, "new", new Object[]{ System.out }).getValue();
        // ambiguous, throws exception
        A a3 = (A)new Expression(
            A.class, "new", new Object[]{ new StringBuilder() }).getValue();
    }
}

Note that the current version doesn’t indicate that the problem is ambiguity in the exceptional case; it’s not distinguishable from the situation when no match has been found.

A fundamental limitation is that there is no way to solve the ambiguity, as you can’t preselect a method or constructor. You would have to resort to low level Reflection with its requirement for exact matches for that.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19355&siteId=1