Java. Method Inner Object as return type

976 views Asked by At

Can I return method local inner object from method?

public class myClass {
    public MyMethodInnerClass getMethodInnerClassObject() {
        class MyMethodInnerClass {
        }
        
        MyMethodInnerClass myMethodClass = new MyMethodInnerClass();
        
        return myMethodClass;
    }
}

throws compilation error. If I can't return my method-local inner class object, then how can I save it after the method returns? How can I reference this object for future usage?


Exception thrown:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: MethodInnerClass cannot be resolved to a type

And also, I'm aware, that local variables in method are stored in stack and deleted just after the method exists.

2

There are 2 answers

0
Peter Lawrey On BEST ANSWER

The scope of your class is inside the method only. You can do this however

public Object getMethodInnerClassObject() {

or

static class MyMethodInnerClass { }

public MyMethodInnerClass getMethodInnerClassObject() {
    return new MyMethodInnerClass();
}
0
the Hutt On

I know it's a bad design. But just for fun, you can use this object outside the method using reflection.

public class Test{
    public static void main(String[] args) throws Exception {
        Outer o = new Outer();
        Outer.Inner in = o.new Inner();
        //method local object
        Object localObj = in.printInner();
        //abusing reflection
        localObj.getClass().getMethods()[0].invoke(localObj);
    }
}

class Outer {
    class Inner{
        
        Object printInner() {
            class LocalInner {
                public void printLocal() {
                    System.out.println("Inside local inner... :P");
                }
            }
            return new LocalInner();
        }
    }
}

This prints:

Inside local inner... :P