简体   繁体   中英

How can I access a method that is inside a class that is inside another method of another class in Java

Below is the program which compiles successfully but how do I access m2() method of class B that is inside m1() method of class A.

class A{  
    public void m1()
    {
      System.out.println("A-m1"); 
        class B{
            public void m2()
            {
                System.out.println("B-m2");
            }
        }//end of class B
    }//end of m1() method
}// end of class A

It all depends on the scope. If you want to invoke m2() at the end of m1() , it's as simple as creating a new instance of B and calling the method.

new B().m2()

If you want to call it outside the method or before the declaration, it won't allow you because of scope.

If that is the case, you should consider promoting its scope to class-level.

Simple: you can't outside of the the class (well, not in a reasonable way).

B is a local class - it only exists within the scope of that method m1() . Therefore you can only instantiate it within that method. So, within m1(), you can do a simple B b = new B() and then invoke b.m2() . But outside of that method, there is no syntax that would allow you to "get" to A.m1().B.m2() .

Well, you can also instantiate it outside of that method using reflection. You see, the mangled name of the class is A$1B.class.

Therefore you could use Class.forName("A$1B") to get the corresponding class; and when you then have an instance of class A, you can again use reflection to instantiate an object of that local class. And on that instance, you could then call m2() - again using reflection.

But: you should not even try to do that. If that class B and its method m2() is required to be called from other places, then simply do not make it a local class. Make it an inner class, or even a (non-public maybe) top level class.

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