Dynamically invoke methods of abstract class?

Hi,
I am using reflection to write a class (ClassA) to dynamically invoke methods of classes. I have an abstract class (ClassB) that has some of the methods already implemented, and some of the methods that are declared abstract. Is there any way that I can:
(a) invoke the methods that are already implemented in ClassB;
(b) I have another class (ClassC) that extends ClassB, some of the methods are declared in both classes. Can I dynamically invoke these methods from ClassB?
Thanks in advance,
Matt.

Ok, the program is quite long, as it does other things as well, so I'll just put in the relevant bits.
What I have is a JTree that displays classes selected by the user from a JFileChooser, and their methods.
// I declare a variable called executeMethod
private static Method executeMethod;
// objectClass is a class that has been chosen by the user.  I create a new instance of this class to execute the methods.
Object createdObject = objectClass.newInstance();
// methodName is the method selected by the user.  objectClassMethods is an array containing all the methods in the chosen class.
executeMethod = objectClassMethods[j].getDeclaringClass().getMethod(methodName, null);
Object executeObject = executeMethod.invoke(createdObject, new Object[]{});Ok, here are the test classes:
public abstract class ClassB{
     private int age;
     private String name;
     public ClassB(){ age = 1; name="Me";}
     public int getAge(){ return age; }
     public String getName(){ return name; }
     public void PrintAge(){System.out.println(age);}
     public void PrintName(){System.out.println(name);}
     public abstract void PrintGreeting();
public class ClassC extends ClassB{
     public ClassC(){super();}
     public void PrintAge(){
          System.out.println("I am " + getAge() + " years old.");
     public void PrintGreeting(){
       System.out.println("Hello");
}Now, I can print out the PrintAge method from ClassC (i.e. have it output "Hello" to the command line, how can I, say, get it to output the result of PrintName from ClassB, this method does not appear in ClassC. As you can see at the top, I can create a new instance of a normal method (in this case, ClassC), and have it output to the command line, but I know that I can't create a new instance of an abstract class. And since PrintName is implemented in abstract class ClassB, how do I get it to output to the command line?
Thanks,
Matt.

Similar Messages

  • How to create dynamically a method of a class??

    I would like to create dynamically a method of a class. Is this possible?
    By means of a report I would like to choose a class, to which the defined method should be added and after that I would like to define the name of the method and its parameters. The result should be, that the method is added to the selected class.
    How to do this?
    Regards
    Christian

    Christian,
    looks like an interesting development project. Though I share the doubts Rich has.
    Anyway, what you could possibly do is, start a runtime analysis for SE24, open an existing class, create a new method including desired interface parameters.
    Then analyze it and see what functions/methods are used.
    But It might be more complex than expected.
    Regards,
    Clemens

  • Can i call non -abstract method in abstract class into a derived class?

    Hi all,
    Is it possible in java to call a non-abstract method in a abstact class from a class derived from it or this is not possible in java.
    The following example will explain this Ques. in detail.
    abstract class A
    void amethod()
    System.out.println(" I am in Base Class");
    public class B extends A
    void amethod()
    System.out.println(" I am in Derived Class");
    public static void main (String args[])
    // How i code this part to call a method amathod() which will print "I am in Base Class
    }

    Ok, if you want to call a non-static method from a
    static method, then you have to provide an object. In
    this case it does not matter whether the method is in
    an abstract base class or whatever. You simply cannot
    (in any object oriented language, including C++ and
    JAVA) call a nonstatic method without providing an
    object, on which you will call the method.
    To my solution with reflection: It also only works,
    if you have an object. And: if you use
    getDeclaredMethod, then invoke should not call B's
    method, but A's. if you would use getMethod, then the
    Method object returned would reflect to B's method.
    The process of resolving overloaded methods is
    performed during the getMethod call, not during the
    invoke (at least AFAIK, please tell me, if I'm wrong).You are wrong....
    class A {
        public void dummy() {
             System.out.println("Dymmy in A");
    class B extends A {
         public void dummy() {
              System.out.println("Dymmy in B");
         public static void main(String[] args) throws Exception {
              A tmp = new B();
              Class clazz = A.class;
              Method method = clazz.getDeclaredMethod("dummy", null);
              method.invoke(tmp, null);
    }Prints:
    Dymmy in B
    /Kaj

  • Protected methods in abstract classes

    Hello All
    I have some problem which I cannot find a workaround for.
    I have three classes:
    package my.one;
    public abstract class First {
      protected void do();
      protected void now();
    package my.one;
    public class NotWantToHave extends First {
      protected First obj;
      public NotWantToHave(First O) { obj = O; }
      public void do() { obj.do(); }
      public void now() { obj.now(); }
    package my.two;
    public class Second extends my.one.First {
      protected void do() { System.out.println("Second does"); }
      protected void now() { System.out.println("Second does now"); }
    package my.three;
    public class Three extends my.one.First {
      protected my.one.First obj;
      public Three(my.one.First O) { obj = O; }
      protected void do() { System.out.println("Doing"); }
      protected void now() { obj.now(); } // Not possible, see later text
    Problem is, as one can read in http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html , it says that you cannot access protected members and methods from classes if they are in a different package. However, since my class Three should not concern about the method now() but should use from some other class that implements (i.e. class Second), the question I have is how to do?
    One way would be to implement a class that simply make a forward call to any protected method in the same package the abstract class is in like in class NotWantToHave and pass it to the constructor of class Third while this class was created with an instance of class Second. However, such a call would look very clumsy (new my.three.Third(new my.one.NotWantToHave(new my.two.Second()));). Furthermore, everyone could create an instance of class NotWantToHave and can invoke the methods defined as protected in class First, so the access restriction would be quite useless.
    Does anyone has a good idea how to do?

    Hi
    One way I found is to have a nested, protected static final class in my super-class First and provide a protected static final method that returns a class where all methods of the super-class are made public and thus accessible from sub-classes at will. The only requirement is that a sub-class must invoke this method to encapsulate other implementations of the super-class and never publish the wrapper class instance. This will look as follows:
    package my.one;
    public abstract class First {
      protected final static class Wrap extends First { // extend First to make sure not to forget any abstract method
        protected First F;
        public void do() { F.do(); }
        public void now() { F.now(); }
        protected Wrap(First Obj) { F = Obj; }
      } // end Wrap
      protected final static First.Wrap wrap(First Obj) { return new First.Wrap(Obj); }
      protected abstract void do();
      protected abstract void now();
    } // end First*******
    package my.two;
    public class Second extends my.one.First {
      protected void do() { System.out.println("Second does"); }
      protected void now() { System.out.println("Second does now"); }
    } // end Second*******
    package my.three;
    public class Three extends my.one.First {
      protected my.one.First.Wrap obj;
      public Three(my.one.First O) { obj = my.one.First.wrap(O); }
      protected void do() { System.out.println("Doing"); }
      protected void now() { obj.now(); } // Not possible, see later text
    } // end Third*******
    In this way, I can access all methods in the abstract super class since the Wrap class makes them public while the methods are not accessible from outside the package to i.e. a GUI that uses the protocol.
    However, it still looks clumsy and I would appreciate very much if someone knows a more clear solution.
    And, please, do not tell me that I stand on my rope and wonder why I fall down. I hope I know what I am doing and of course, I know the specification (why else I should mention about the link to the specification and refer to it?). But I am quite sure that I am not the first person facing this problem and I hope someone out there could tell me about their solution.
    My requirements are to access protected methods on sub-classes of a super-class that are not known yet (because they are developed in the far, far future ...) in other sub-classes of the same super-class without make those methods public to not inveigle their usage where they should not be used.
    Thanks

  • Final methods in abstract classes?

    Hi, why is it possible to define a final method in an abstract class? The theory behind a final method doesn't say that a final method couldn't be overridden?
    Marco

    So it's formally correct but it doesn't have any
    sense, does it?You sound very confused. A final method in an
    abstract class has just the same semantics and
    makes just as much sense as in a non-abstract
    class.
    The semantics of a final method is simply that
    it cannot be overridden in subclassed. Both
    abstract and non-abstract classes can be
    subclasses. So why do you think there should be any
    difference?Actually i was confused now it's clear. I was too binded to the concept that the extending class SHOULD(not for a formal reason, but for a 'design' one) write the implementation of the methods defined in the abstract class. Now i see that, actually, by defining a final method in an abstract class we are defining our design as implemented and clients(i.e. subclasses) can only use it.
    Thank you,
    Marco

  • I really need abstract static methods in abstract class

    Hello all.. I have a problem,
    I seem to really need abstract static methods.. but they are not supported.. but I think the JVM should implement them.. i just need them!
    Or can someone else explain me how to do this without abstract static methods:
    abstract class A {
    abstract static Y getY();
    static X getX() {
        // this methods uses getY, for example:
        y=getY();
       return new X(y); // or whatever
    class B extends A {
    static Y getY() { return YofB; }
    class C extends A {
    static Y getY() { return YofC; }
    // code that actually uses the classes above:
    // these are static calls
    B.getX();
    A.getX();I know this wont compile. How should i do it to implement the same?

    Damn i posted this in the wrong thread.. anyways.
    Yes offcourse i understand abstract and static
    But i have a problem where the only solution is to use them both.
    I think it is theoretically possible ot implement a JVM with support for abstract static methods.
    In fact it is a design decision to not support abstract static methods.. thats why i am asking this question.. how could you implemented this otherwise?
    There is an ugly soluition i think: using Aspect Oriented Programming with for example AspectJ.. but that solution is really ugly. So anyone has an OO solution?

  • Implement method inside abstract class?

    hello everyone:
    I have a question regarding implementation of method inside a abstract class. The abstract class has a static method to swamp two numbers.
    The problem ask if there is any output from the program; if no output explain why?
    This is a quiz question I took from a java class. I tried the best to recollect the code sample from my memory.
    if the code segment doesn't make sense, could you list several cases that meet the purpose of the question. I appreciate your help!
    code sample
    public abstract class SwampNumber
       int a = 4;
       int b = 2;
       System.out.println(a);
       System.out.println(b);
       swamp(a, b);
       public static void swamp(int a, int b)
         int temp = a;
             a = b;
             b = a;
         System.out.println(a);
         System.out.println(b);

    It won't compile.
    You can't instantiate an abstract class before you know anything.
    //somewhere in main
    SwampNumber myNum = new SwampNumber();
    //Syntax ErrorQuote DrClap
    This error commonly occurs when you have code that >>is not inside a method.
    The only statements that can appear outside methods >>in a Java class are >>declarations.Message was edited by:
    lethalwire

  • Using common methods with abstract classes

    hello everyone, i wanted to know if it is bad practice (i imagine it is) to place methods which will be used by multiple classes (computational methods) in an abstract class and mark them as static. When i do this they are always project wide utility classes which dont need an instantiation. When using any of these methods which are common to a project i can then just use..
    Type result = ClassName.DoStaticMethod(...);Thanks for any input,
    Dori
    Edited by: Sir_Dori on Dec 8, 2008 2:01 AM

    Depends on what the methods are meant to do, but I wouldn't make the class abstract. I would instead declare it to be final and have a private constructor.
    Kaj
    Ps. Take a look at the java.lang.Match class.

  • Non-abstract methods in a Abstract class

    Abstract Class can contain Non-abstract methods.
    and Abstract Classes are not instantiable as well
    So,
    What is the purpose of Non-abstract methods in a Abstract class.
    since we can't create objects and use it
    so these non-abstract methods are only available to subclasses.
    (if the subclass is not marked as abstract)
    is that the advantage that has.(availability in subclass)
    ??

    For example, the AbstractCollection class (in
    java.util) provides an implementation for many of the
    methods defined in the Collection interface.
    Subclasses only have to implement a few more methods
    to fulfill the Collection contract. Subclasses may
    also choose to override the AbstractCollection
    functionality if - for example - they know how to
    provide an optimized implementation based on
    characteristics of the actual subclass.Another example is the abstract class MouseAdapter that implements MouseListener, MouseWheelListener, MouseMotionListener, and that you can use instead of these interfaces when you want to react to one or two types of events only.
    Quoting the javadocs: "If you implement the MouseListener, MouseMotionListener interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you can only have to define methods for events you care about."

  • Access overriden method of an abstract class

    class Abstract
    abstract void abstractMethod(); //Abstract Method
    void get()
    System.out.print("Hello");
    class Subclass extends Abstract
    void abstractMethod()
    System.out.print("Abstract Method implementation");
    void get()
    System.out.print("Hiiii");
    In the above code, i have an abstract class called "Abstract", which has an abstract method named "abstractMethod()" and another method called "get()".
    Now, this class is extended by "Subclass", it provides implementation for "abstractMethod()", and also overrides the "get()" method.
    Now my problem is that i want to access the "get()" method of "Abstract" class. Since it is an abstract class, i cant create an object of it directly, and if i create an object like this:
    Abstract obj = new Subclass();
    then, obj.get() will call the get() method of Subclass, but how do i call the get() method of Abstract class.
    Thanks in advance

    hey thanks a lot,, i have another doubt regarding Abstract classes.
    i was just trying something, in the process, i noticed that i created an abstract class which does not have any abstract method, it gave no compilation errors. was wondering how come this is possible, and what purpose does it solve?

  • Abstract class method polymorphically using constructors?

    how can i have a method defined in an abstract superclass call a constructor of the actual class running the method?
    abstract class A {
    public List getMultple() {
    List l = new ArrayList();
    for (short i=0;i<4;i++) {
    l.add(this());//<obviously this breaks
    return l
    or something like that. A won't run this method, but its children will...and they can call their constructors, but what do i put here to do that?
    i've tried a call back. an abstract method getOne() in the superclass forces each child to define that method and in each of those i return the results of a constructor. that works fine.
    the problem is i want to abstract this method out of each of these children classes cause its the exact same in each one, just using a different constructor to get multiple of each in a list. so if i use this callback method, then i am not saving the number of methods in each class, so why bother at all?
    any ideas?

    I still say you are coming at it from the wrong angle. A super class is not the way to go. What you are doing sounds like something very similar to something I did not too long ago.
    My requirement was that I had tab delimited text files filed with data that I had to parse. Each line would be used to instantiate one object, so a particular file could be used to instantiate, for example, a thousand objects of the same class. There were different types of files corresponding to different classes to instantiate instances of.
    Here is the design I ended up using.
    An object of class DataTextFileReader is instantiated to parse the text file and generate objects. It includes code for going line by line, handling bad lines and generating objects and reports. The constructor:
    public DataTextFileReader(File inputFile, LineParser<T> theLineParser)LineParser is an interface with one method:
    public T read(String line);When you call a load() method of the DataTextFileReader, it does its thing with the aid of the LineParser's read method, to which each line is passed, and stores the generated objects in an ArrayList. This can be returned by using another method. There are other methods for getting the reports, etc.
    Obviously, the LineParser chosen needs to have code appropriate for parsing the lines in question, so you have to choose and instantiate the right one.
    I find this design to work well. I arrived at it after spending hours giving myself headaches trying to come up with a design where there was a superclass roughly equivalent to the DataTextFileReader mentioned above, and classes extending this that fulfilled the duty of the LineParsers mentioned above... rather like what you are trying to do now.
    I did not care for the solution at first because it did not give me the "Ah, I am clever!" sensation I was expecting when I finally cracked the problem using inheritance, but I quickly came to think that it was much better OOD anyway.
    The LineParsers mentioned above are essentially embodiments of the Factory pattern, and I would recommend you do something similar in your case. Obviously your "constructors" all have to be different, so you should make a separate class for each of those. Then you can put the code that performs the query and loops to create loads of objects in another class called something like DatabaseDepopulator, using appropriate generics as in my example. Really it is the same problem, now that I look at it.
    This will also result in better separation of concepts, if you ask me. Why should the class constructor know how to parse a database result query, much less perform the query? It has nothing to do with databases (I presume). That is the job of an interpreter object.
    As a final note, remember... 95% of the time you feel like the language won't let you do what you want, it is because you shouldn't anyway.
    Drake

  • Invoking method of final subclass of abstract class is slow

    hi,
    I've diagnosed a performance regression in my code which boils down to the example at the end of the post.
    Would it be possible to have the vm dynamically figure out that within the hotspot in the test method, its
    safe to ditch the dynamic dispatch and skip that overhead?
    I thought marking the method as final would allow the vm to peform some run-time optimisations - I'm pretty sure I've been able to measure that in different situations; marking the test method's parameter (a) as final, also doesn't help.
    Rather than have an abstract class, its looking like the performance requirements will dictate some copy and paste to
    help the vm along - does anyone know if I'm missing something here?
    thanks in advance,
    asjf
    The output I see (using 6.0 update 10) is:
    B foo 28
    B bar 95
    C foo 29
    C bar 86
    D foo 26
    D bar 92
    E foo 29
    E bar 82
    public class MethodCallPerfTest {
         public static void main(String[] args) {
              test(new B());
              test(new C());
              test(new D());
              test(new E());
         public static void test(A a) {
                   long start= System.currentTimeMillis();
                   for(int i=0; i<8000000; i++)
                        a.foo();
                   System.out.println(a.getClass().getSimpleName()+" foo "+(System.currentTimeMillis() - start));
                   long start= System.currentTimeMillis();
                   for(int i=0; i<8000000; i++)
                        a.bar();
                   System.out.println(a.getClass().getSimpleName()+" bar "+(System.currentTimeMillis() - start));
    abstract class A {
         int j;
         final void foo() {j++;}
         abstract void bar();
    final class B extends A {
         int k;
         void bar() {k++;}
    final class C extends A {
         int l;
         final void bar() {l++;}
    class D extends A {
         int m;
         final void bar() {m++;}
    class E extends A {
         int n;
         void bar() {n++;}
    }

    is it because references to the final fields are resolved at compile-time ?
    such that the compiler must know the value of USE in:if(USE){
      // a
    // b at compile time so it can remove either "b" or "a". I think so. hmm.

  • Calling a super.ssuper.method but your super is a abstract class.

    Dear guys,
    Is that possible to invoke your super's super's method but your super is a abstract class?
    like:
    class GO {   public void draw() { } }
    abstract class GORunner extends GO {}
    class GOCounter extends GORunner {
    public void draw() {
    super.super.draw();
    I want to do this because I would like to take advantages of the abstract as an layer to achieve some polymorphism programming Therefore, in the later stage of the programming some code may only refer to GORunner but actually it is holding a GOCounter object.
    Thank!!

    BTW you don't need to write this
    public void draw() {
       super.draw();
    }It works but its basically the same as not having it at all.

  • Why does this abstract class and method work without implement it?

    hi,
    I have seen many times that in some examples that there are objects made from abstract classes directly. However, in all books, manual and tutorials that I've read explain that we MUST implement those methods in a subclass.
    An example of what I'm saying is the example code here . In a few words that example makes Channels (java.nio.channel) and does operations with them. My problem is in the class to make this channels, because they used the ServerSockeChannel class and socket() method directly despite they are abstracts.
       // Create a new channel: if port == 0, FileChannel on /dev/tty, else
       // a SocketChannel from the first accept on the given port number
    private static ByteChannel newChannel (int netPort)
          throws Exception
          if (netPort == 0) {
             FileInputStream fis = new FileInputStream ("/dev/tty");
             return (fis.getChannel());
          } else {
    //CONFLICT LINES
             ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
             ssc.socket().bind (new InetSocketAddress (netPort)); //<--but here, this method (socket) is abstract. WHY RETURN A SOCKET????????  this mehod should be empty by default.
             System.out.print ("Waiting for connection on port "
                + netPort + "...");
             System.out.flush();
             ByteChannel channel = ssc.accept();
             ssc.close();
             System.out.println ("Got it");
             return (channel);
       } I test this code and works fine. So why can it be??
    Also, I read that the abstract classes can't have static methods. Is it true???
    Please Help!!
    PS: i have seen this kind of code many times. So i feel that I don't understand how its really the abstract methods are made.
    PS2: I understand that obviously you don't do something like this: *"obj = new AbstractClass(); "*. I dont understand how it could be: ServerSocketChannel ssc = ServerSocketChannel.open(); and the compiler didn't warn.

    molavec wrote:
    ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
    The static method creates an instance of a class which extends ServerSocketChannel, but is actually another non-abstract class.I thought that, but reading the documentation I saw that about open() method:
    Opens a server-socket channel.
    The new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object.
    The new channel's socket is initially unbound; it must be bound to a specific address via one of its socket's bind methods before connections can be accepted.
    ...and the problem is the same openServerSocketChannel is abstract, so i don't understand how it could return a ServerSocketChannel.There is a concrete implementation class that has implemented that method.
    I guess that really the open() method use a SelectorProvider's subclase but it doesn't appear in the doc.It doesn't need to. First, you don't care about those implementation details, and second, you know that if the class is abstract, it must use some concrete subclass.
    Ok, I speak Spanish by default (<-- this sounds like "I am a machine", ^_^' ). So, I didn't know how to say that the method would be {}. Is there a way to say that?? I recommendable for me to know, for the future questions o answers.Not sure what you're saying here. But the other respondent was trying to explain to you the difference between an abstract method and an empty method.
    // abstract method
    public abstract void foo();
    // empty method
    public void bar() {
    Which class does extend ServerSocketChannel? I can not see it.It may be a package-private class or a private nested class. There's no need to document that specific implementation, since you never need to use it directly.

  • How to invoke method dynamically?

    hai forum,
    Plz let me know how do we invoke a dynamically choosen method method[ i ] of a class file by passing parameter array, para[ ].The structure of my code is shown below.. How will i write a code to invoke the selected method method?Plz help.
    public void init()
    public void SelectClass_actionPerformed(ActionEvent e)
    //SELECT A METHOD method[ i ] DYNAMICALLY HERE
    private void executeButton1_mouseClicked(MouseEvent e) {
    //GET PARAMETERS para[ ] HERE.
    //METHOD SHOULD BE INVOKED HERE
    }//end of main class

    Often,a nicer way would be to create an interface like "Callable" with one single "doMagic()" method, and different classes implementing this interface, instead of one class with different methods. Then simply load the class by name, call newInstance(), cast to Callable and invoke doMagic(). Keeps you away from most of the reflection stuff.

Maybe you are looking for