简体   繁体   English

爪哇。 方法内部对象作为返回类型

[英]Java. Method Inner Object as return type

Can I return method local inner object from method?我可以从方法返回方法本地内部对象吗?

public class myClass {
    public MyMethodInnerClass getMethodInnerClassObject() {
        class MyMethodInnerClass {
        }

        MyMethodInnerClass myMethClass = new MyMethodInnerClass();

        return myMethClass;
    }
}

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线程“main”中的异常java.lang.Error:未解决的编译问题:MethodInnerClass无法解析为类型

And also, I'm aware, that local variables in method are stored in stack and deleted just after the method exists.而且,我知道,方法中的局部变量存储在堆栈中,并在方法存在后立即删除。

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();
}

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在本地内部... :P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM