Question

I'm learning about reflection in Java and i have a little problem - I would like to invoke two methods - First I would like to set the location of my jframe and in the second one add buttons to it.

But unfortunately in both my methods I receive StackOverflowError and it looks like my method invoke was invoked more than once...

I read some faq and tutorials on how to use invoke methods but I am doing something wrong...

Could anybody help me please?

public class zad2 extends JFrame{

public int setLocationtest(int x, int y){

    setLocation(x,y);
    return 1;
}
public void addButton(String txt){

    add(new JButton("Przycisk 1"+txt));

}


    zad2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        super("tytuł");
        getContentPane().setLayout (new GridLayout(2,2));
        setSize(300,300);
        setLocation(350,50);



        Method testMethod = zad2.class.getDeclaredMethod("setLocationtest", Integer.TYPE, Integer.TYPE);
        testMethod.setAccessible(true);
        testMethod.invoke(new zad2(), 10, 10);
        //setLocationtest(20,50);

        Method testMethodbt = zad2.class.getDeclaredMethod("addButton", String.class);

        testMethodbt.invoke(new zad2(), "1");

        setVisible(true);       

    }

public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    new zad2();

}

}

Was it helpful?

Solution

Your constructor zad2 is creating another instance of zad2 here:

testMethodbt.invoke(new zad2(), "1");

That will call the same constructor on another instance, which will create its own new zad2(), and so on, and this will continue until the stack overflows.

If you meant to invoke the method on the current instance, pass this instead of a new zad2.

This applies also to the earlier line in the constructor:

testMethod.invoke(new zad2(), 10, 10);

Of course it raises the question of why reflection is needed, when a straight method call would suffice here.

OTHER TIPS

zad2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    // blah blah . . .
    testMethod.invoke(new zad2(), 10, 10);

see the recursion? new zad2() -> new zad2() -> new zad2() . . .

Try using this instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top