The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
July 2000

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

RE: call subclass method from a superclass

Posted by Kishori Sharan on July 05, 2000 at 2:38 PM

Note that I haven't written code for catching the execptions, instead I am throwing the exceptions to console. You should put your getMethod () and invoke () methods inside try blocks. One thing is important here is to declare m2 () as public because getMethod () method of class Class can get you only public method. If you don't want to declare m2() public then you can use getDeclaredMethod ( ) method of Class class which returns an array of Method object which includes all classes and then from array get your method reference and invoke the method.

// Import java.lang.reflect to use Method class
import java.lang.reflect.* ;

// A is your super class and B is sub class. I am calling method m2 on an object of class B from a method in class A.
class A {

void m1 ( A a) throws Exception {

// Get the class of the object
Class cls;
cls = a.getClass ( ) ;

// Get the "m2" method reference for the object
String[] methods ;
Method mymethod , mymethods[];
Class[] myclasses = null ;

// Get the method m2 ( )
/* Note that we have set myclasses to null because m2 ( )
method takes no parameters */
// You need to put the folloing line within try block
// and catch the possible exceptions

mymethod = cls.getMethod ("m2", myclasses ) ;

// Invoke the method m2
/* Again note that args has been set to null to indicate there is no parameters */
// Use try block
Object[] args = null;
mymethod.invoke ( a, args ) ;


}
}

class B extends A {

public void m2 ( ) {
System.out.println ( "Hello. m2 for B is called" ) ;
}
}

public class SuperSub {

public static void main ( String[] args ) throws Exception {
A a_obj = new A ( );
B b_obj = new B ( ) ;
a_obj.m1 ( b_obj ) ;
}

}

Thanx
Kishori




Replies:
  • reg my doubts mala February 01, 2001 at 2:20 AM (2)
    • doubt chandu May 03, 2001 at 7:10 AM (1)
      • reply.... Ramaz January 18, 2002 at 12:56 AM (0)
  • solution Erik Buitenhuis July 18, 2000 at 4:11 AM (0)

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us