- getXXXClass方法获取class对象
在讲解具体的方法之前,我们先介绍一下java类(接口)的划分方法。
java的class对象分为5种,这一点在getEnclosingClass方法的注释中有写明,分别是:
a. Top类
b. Nested类:嵌套类,即静态成员类
c. Inner类:内部类,即普通成员类
d. Local类:局部类,在方法中定义的类
e. Anonymous:匿名类
Class对象有3个和name相关的方法,分别是getClass, getDeclaringClass和getEnclosingClass,下面我们仔细看一下这3个方法有什么区别。
-
getClass方法
getClass方法是从Object类继承而来的方法,返回的是该对象所对应的运行时类。
class.getClass()返回的自然是java.lang.Class. -
getDeclaringClass方法
从注释可以看出,class.getDeclaringClass()方法返回了声明class对象的类,只有当class对象的类A是另一个类B的成员类,该方法才能返回值,返回该成员类所在的类(即类B),否则返回null值。
如果class对象是local class,是在类B的方法里定义的,同样返回null值,而不会返回类B。
/**
* If the class or interface represented by this {@code Class} object
* is a member of another class, returns the {@code Class} object
* representing the class in which it was declared. This method returns
* null if this class or interface is not a member of any other class. If
* this {@code Class} object represents an array class, a primitive
* type, or void,then this method returns null.
* * @return the declaring class for this class
* @throws SecurityException
* If a security manager, <i>s</i>, is present and the caller's
* class loader is not the same as or an ancestor of the class
* loader for the declaring class and invocation of {@link
* SecurityManager#checkPackageAccess s.checkPackageAccess()}
* denies access to the package of the declaring class
* @since JDK1.1
*/
@CallerSensitive
public Class<?> getDeclaringClass() throws SecurityException {
final C