简体   繁体   中英

How to return object of private inner class object java

How can I return the object of a private inner class

public class MainClass{
   public InnerClass getObj(){
       return this.new InnerClass()
   }
   private class InnerClass{
       InnerClass(){
       }
   }
}
-------------
MainClass mc = new MainClass();
mc.getObj(); // assume I am not holding it anywhere.

The above code is giving a null pointer exception, when I checked with the try-catch blocks. Also, when tried in debug mode, its says ' ClassNotFoundException '

But I can see the class file generated as MainClass$InnerClass.class

Hmmm, I'm not having that same problem. Here's my modified version of your code:

class MainClass {
    public static void main( String[] args ) {
        MainClass mc = new MainClass();
        InnerClass ic = mc.getObj();
        System.out.println( ic );
    }

    public InnerClass getObj() {
        return this.new InnerClass();
    }

    private class InnerClass {
        InnerClass() {}
    }
}

The result of this code is:

MainClass$InnerClass@64c3c749

As others have already pointed out all you need to do is fix the return type of your method.

However, you should be aware that you'll get a warning since you're exporting a non-public type in a public method.

Since your getObj() is public, you should either keep the inner class private and return an Object , or make it public and return an InnerClass , depending on your needs.

The following code returns an object in example:

public class MainClass {
        private class InnerClass {
                InnerClass() { System.out.println("InnerClass"); }
        }

        public Object getObj(){
                return new InnerClass();
        }

        public static void main (String[] argc) {
                MainClass a = new MainClass();
                System.out.println(a.getObj());
        }
}

It prints out:

bash-4.2$ java MainClass
InnerClass
MainClass$InnerClass@53c059f6

As you can see there are no problems with the constructor.

You simply forgot the return type of your getObj method.

 public InnerClass getObj(){return new InnerClass();}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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