Class对象的getXXXClass和getXXXName

  1. 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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值