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:long.classwould be valid for aLongvalue inargs)Stringarguments, you may want to consider that valid for a method offoo(String... args))Class.isAssignableFrom)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 🙂