views:

313

answers:

3

Is it possible to invoke the no modifier method in a superclass through Java reflection?

+1  A: 

Yes. You may need to call setAccessible(true) on the Method object before you invoke it.

Russ Hayward
both getMethod and getDeclaredMethod fail if called on the subclass. and setAccessible is not required.
Bozho
From that comment i'd guess you're trying to call a method with parameters. You need to specify these when looking up the Method.
Stroboskop
I'm not the OP ;)
Bozho
+2  A: 
Method method = getClass().getSuperclass().getDeclaredMethod("doSomething");
method.invoke(this);

if you have a bigger hierarchy, you can use:

Class current = getClass();
Method method = null;
while (current != Object.class) {
     try {
          method = current.getDeclaredMethod("doSomething");
          break;
     } catch (NoSuchMethodException ex) {
          current = current.getSuperclass();
     }
}
// only needed if the two classes are in different packages
method.setAccessible(true); 
method.invoke(this);

(the above examples are for a method named doSomething with no arguments. If your method has arguments, you have to add their types as arguments to the getDeclaredMethod(...) method)

Bozho
Wouldn't it be better to get back `Method[]` using `getDeclaredMethods()` and checking to see if we have a method name that matches rather than catching the exception? Isn't the latter rather slow because a stack trace has to be generated each time? Or am I optimizing prematurely? :)
Vivin Paliath
+1  A: 

After reading the original question -- I realize I assumed you were trying to call an overridden method. Which is what I was trying to do and how I came to find this thread. Calling a base class non-overridden method should work as others here have described. However, if you are trying to call an overridden method, my answer stands as below:

I don't think calling an overridden method is possible, per

http://blogs.sun.com/sundararajan/entry/calling_overriden_superclass_method_on

Most notably:

Method.invoke

If the underlying method is an instance method, it is invoked using dynamic method lookup as documented in The Java Language Specification, Second Edition, section 15.12.4.4; in particular, overriding based on the runtime type of the target object will occur.

oldag