2010-10-29 134 views
7

简而言之,我试图去做“classObject.getDeclaredClasses()”的反例。从内部类对象中获取外部类对象

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

是否有一个聪明的API,或者我不得不做一些字符串操作和解析?

回答

20

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

公共类getDeclaringClass()

如果此Class对象所表示的类或接口是 另一个类的成员,返回表示类对象它在其中声明的类别 。如果此类或接口不是任何其他类的 成员,则此方法返回null。如果这个Class对象表示一个数组类,或者一个原始类型,或者void,那么这个方法返回null。

返回:声明类该类

+0

唉的一个实例被实例化,我感到笨。当然,我正在寻找这个。谢谢! – 2010-10-29 11:18:48

1

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

如果内部类代码需要,它连接到外部类实例的引用,使用外部类,一个点的名称,这

* 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 
相关问题