Java反射之Class类一

Class类

 所在包为java.lang

public final class Class<T> implements java.io.Serializable,
                              GenericDeclaration,
                              Type,
                              AnnotatedElement {

》实现了Serializable,代表可序列化

》实现了Type接口

/**
 * Type is the common superinterface for all types in the Java
 * programming language. These include raw types, parameterized types,
 * array types, type variables and primitive types.
 *
 * @since 1.5
 */
public interface Type {
    /**
     * Returns a string describing this type, including information
     * about any type parameters.
     *
     * @implSpec The default implementation calls {@code toString}.
     *
     * @return a string describing this type
     * @since 1.8
     */
     //返回当前类的类型名称
    default String getTypeName() {
        return toString();
    }
}

2、属性

3、构造方法

只有一个私有的构造方法,需要传入一个类加载器ClassLoader

只能有java虚拟机来创建

private Class(ClassLoader loader) {
        // Initialize final field for classLoader.  The initialization value of non-null
        // prevents future JIT optimizations from assuming this final field is null.
        classLoader = loader;
    }

4、方法

  • toGenericString()
/**
     * 返回类的描述,包括修饰符、 类型参数
     * @return
     */
    public String toGenericString() {
        //检查是否为原始类型(基本类型,包括Boolean、Integer等)
        // 是native方法,由虚拟机实现
        if (isPrimitive()) {
            /**
             * 在toString中会判断当前类是interface还是class
             * interface:返回值为interface+接口的名字
             * class:返回值为class+类的名字
             */
            return toString();
        } else {
            StringBuilder sb = new StringBuilder();

            // Class modifiers are a superset of interface modifiers
            /**
             * getModifiers:获取类/接口的所有修饰符,是一个native实现
             *
             * Modifier.classModifiers():所有修饰符的或运算的值,如下:
             * private static final int CLASS_MODIFIERS =
             *         Modifier.PUBLIC         | Modifier.PROTECTED    | Modifier.PRIVATE |
             *         Modifier.ABSTRACT       | Modifier.STATIC       | Modifier.FINAL   |
             *         Modifier.STRICT;
             *
             * modifiers:当前类/接口所拥有的修饰符16进制数
             */
            int modifiers = getModifiers() & Modifier.classModifiers();
            if (modifiers != 0) {
                //将modifiers与所有的修饰符的16进制数进行&运算,
                //得到所有的修饰符并进行拼接
                sb.append(Modifier.toString(modifiers));
                sb.append(' ');
            }

            //如果是注解则需拼接@
            if (isAnnotation()) {
                sb.append('@');
            }
            //接口类型拼接上interface,所有的注解类型都是interface
            //isInterface()是一个native实现
            if (isInterface()) { // Note: all annotation types are interfaces
                sb.append("interface");
            } else {
                /**
                 * 是否为枚举类
                 * 条件1:是否被enum修饰
                 * 条件2:父类是否是Enum类型
                 */
                if (isEnum())
                    sb.append("enum");
                else
                    sb.append("class");
            }
            sb.append(' ');
            sb.append(getName());

            /**
             * getTypeParameters()
             * 获取类型参数,即泛型,如List的泛型参数为E
             */
            TypeVariable<?>[] typeparms = getTypeParameters();
            if (typeparms.length > 0) {
                boolean first = true;
                sb.append('<');
                for(TypeVariable<?> typeparm: typeparms) {
                    if (!first)
                        sb.append(',');
                    /**
                     * typeparm.getTypeName()
                     * 获取类型参数的名字
                     *
                     * 默认实现:Type接口中
                     *
                     * Class重写Type接口的方法:
                     * 区分数组返回名字
                     */
                    sb.append(typeparm.getTypeName());
                    first = false;
                }
                sb.append('>');
            }

            return sb.toString();
        }
    }
  • forName(String className)

   通过name加载指定类

/**
     * 根据入参className返回Class对象
     * @CallerSensitive java8的注解,用来堵住漏洞的,具体可以百度下
     * @param className
     * @return
     * @throws ClassNotFoundException
     */
    @CallerSensitive
    public static Class<?> forName(String className)
            throws ClassNotFoundException {
        /**
         * getCallerClass()是nativa方法,
         * 获取调用者
         */
        Class<?> caller = Reflection.getCallerClass();
        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
    }
  • forName()
**
     * 此方法的作用于forName(String className)方法的作用是类似的,
     * 在SecurityManager不为null的情况下才调用此方法
     * @param name     类的名称
     * @param initialize   是否初始化类
     * @param loader   加载器
     * @return
     * @throws ClassNotFoundException
     */
    @CallerSensitive
    public static Class<?> forName(String name, boolean initialize,
                                   ClassLoader loader)
            throws ClassNotFoundException
    {
        Class<?> caller = null;
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            // Reflective call to get caller class is only needed if a security manager
            // is present.  Avoid the overhead of making this call otherwise.
            caller = Reflection.getCallerClass();
            if (sun.misc.VM.isSystemDomainLoader(loader)) {
                ClassLoader ccl = ClassLoader.getClassLoader(caller);
                if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
                    //检查是否具有累加器的获取的权限
                    sm.checkPermission(
                            SecurityConstants.GET_CLASSLOADER_PERMISSION);
                }
            }
        }
        //本地方法,生成name类
        return forName0(name, initialize, loader, caller);
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值