문제

I'm facing something that I don't think is solvable, but it's worth a try. Assume you have the following classes :

package a;

public class A
{
    protected A() {}

    public static void staticMethod(A a) {
        // ...
    }
}

public class B extends A
{
    public B() {}
}

So you can instantiate B from other packages, but not A. Now assume you want to use Class.getMethod, only you're using some kind of reflexivity framework that goes something like :

public Object callStaticMethod(Class c, String methodname, Object[] args)
{
    Class[] signature = new Class[args.length];
    for (i = 0 ; i < args.length ; ++i) {
        signature[i] = args.getClass();
    }
    Method m = c.getMethod("methodname", signature);
    return m.invoke(null, args)
}

This method is given to me as-is, and sadly I can not improve it. Now you may want to call the method like this :

package b;

B b;
callStaticMethod(A.class, "staticMethod", b);

...Except that will not work, because the signature generated (based on getClass() results will be {B.class}, and there is no method called staticMethod in A which takes a B as parameter.

Would any of you know about that ?

BONUS : As an additional challenge, is there a way, with this method, to call staticMethod with a null parameter (which may also be perfectly valid, semantically)? I personally haven't found a way to.

도움이 되었습니까?

해결책

What you'd have to do is use something like Class.getMethods, then check each candidate method for suitability. You may wish to consider:

  • Boxing (so long.class would be valid for a Long value in args)
  • Varargs (so if you have two String arguments, you may want to consider that valid for a method of foo(String... args))
  • Null compatibility (basically with any class-type parameter)
  • Assignment compatibility (probably via Class.isAssignableFrom)
  • Generics (this will almost certainly prove horrible)

If there are multiple applicable candidate methods, you may want to consider emulating the Java overloading rules - but I'd probably avoid it and go bang if you can :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top