从内部类对象获取外部类对象

11

简而言之,我正在尝试做"classObject.getDeclaredClasses()"的反向操作。

我有一个接收Class<? extends Object>类型对象的方法。我想找出它是否是内部类,如果是,我想访问周围类的对象实例。

是否有智能API可以实现这一点,还是我必须进行一些字符串操作和解析?

2个回答

24

你正在寻找 Class.getDeclaringClass() 方法:

public Class getDeclaringClass()

如果由此 Class 对象表示的类或接口是另一个类的成员,则返回表示声明它的类的 Class 对象。如果此类或接口不是任何其他类的成员,则此方法返回 null。如果此 Class 对象表示数组类、基本类型或 void,则此方法返回 null。

返回值:返回此类的声明类


2
如果问题中的类是匿名的,使用getEnclosingClass会更好。 - Ted Hopp

1

从内部类代码中引用外部类实例

如果内部类代码需要引用它所附加的外部类实例,请使用外部类的名称、一个点和this。

* remember that if there is no name conflict, there is no need for any special syntax
* for code in MyInner to obtain a reference to its MyOuter:

  MyOuter.this

静态内部类

内部类可以被标记为静态

静态内部类可以在没有外部类实例的情况下被实例化

* static members of the outer class are visible to the inner class, no matter what their access level
* non-static members of the outer class are not available, since there is not instance of the outer class to retrieve them from

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接