[英]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. 下面是成功编译的程序,但是如何访问类A的m1()方法中的B类m2()方法。
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. 如果要在
m1()
的末尾调用m2()
,就像创建B
的新实例并调用方法一样简单。
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()
. B是一个本地类 - 它只存在于该方法
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()
. 因此,在m1()中,你可以做一个简单的
B b = new B()
,然后调用b.m2()
。 But outside of that method, there is no syntax that would allow you to "get" to A.m1().B.m2()
. 但是在该方法之外,没有语法允许您“获取”到
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.
你看,这个类的错位名是A $ 1B.class。
Therefore you could use Class.forName("A$1B")
to get the corresponding class; 因此,您可以使用
Class.forName("A$1B")
来获取相应的类; and when you then have an instance of class A, you can again use reflection to instantiate an object of that local class. 然后当你有一个A类实例时,你可以再次使用反射来实例化该本地类的对象。 And on that instance, you could then call m2() - again using reflection.
在那个例子中,你可以再次使用反射调用m2()。
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.
如果需要从其他地方调用类B及其方法m2(),那么就不要使它成为本地类。 Make it an inner class, or even a (non-public maybe) top level class.
使它成为内部阶级,甚至是(非公开的)顶级阶级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.