-2

When I search for the method by reflection it shows the newly provided method. But I don't know how to invoke that method, if someone has got any idea how to do it please tell me.

//some pakage
pakage xyz;

class A {
    // a simple method of class A
    public void aMethod() {
        //simple print statement
        System.out.println("A class method");
    }
}

class B {
    // a method of class B that takes A types as an argument
    public void bMethod(A arg) {
        Class c = Class.forName("xyz.A");

        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
        }
    }
}

class Test {
    public static void main(String[] args) {
        B bObj = new B();
        bObj.bMethod(new A() {
            public void anotherMethod() {
                System.out.println("another method");
            }
        });
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
Ankur
  • 29
  • 1
  • 10
  • Please format your code first. – chaos May 31 '17 at 08:33
  • I formatted your question and your code, and fixed the obvious mistakes. Next time, I'll just downvote. Take some care when writing a question. – JB Nizet May 31 '17 at 08:36
  • 1
    You should also explain what you're trying to achieve, at a much higher level. Why are you using reflection? Why are you using such anonymous classes with additional methods that no one can call. But anyway, if you want to find this additional method, you need to get the methods of the class of `arg`. Not the methods of A. – JB Nizet May 31 '17 at 08:38
  • Thank you https://stackoverflow.com/users/571407/jb-nizet – Ankur Jun 01 '17 at 10:26

2 Answers2

0

You can use reflection to invoke the method on particular object:

public void invokeSomeMethodOnA(A arg, String methodName) {
    Method method = arg.getClass().getDeclaredMethod(methodName);

    //To invoke the method:
    method.invoke(arg, parameters here);
}
Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
0

I suppose maybe this is what you want.

package xyz;

import java.lang.reflect.Method;

class A {
    // a simple method of class A
    public void aMethod() {
        //simple print statement
        System.out.println("A class method");
    }
}

class B {
    // a method of class B that takes A types as an argument
    public void bMethod(A arg) throws Exception {
        Class c = Class.forName(arg.getClass().getName());

        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
            method.invoke(arg);
        }
    }
}

class Test {
    public static void main(String[] args) throws Exception {
        B bObj = new B();
        bObj.bMethod(new A() {
            public void anotherMethod() {
                System.out.println("another method");
            }
        });
    }
}
chaos
  • 1,359
  • 2
  • 13
  • 25