`
Charles2628
  • 浏览: 2615 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

leaning for Class---1

阅读更多

首先看看Class 的声明:

public final

    class Class implements java.io.Serializable,

                              java.lang.reflect.GenericDeclaration,

                              java.lang.reflect.Type,

                              java.lang.reflect.AnnotatedElement

 

Final 的,而且支持泛型,实现了某些接口。

/**

* Instances of the class {@code Class} represent classes and

* interfaces in a running Java application.  An enum is a kind of

* class and an annotation is a kind of interface.  Every array also

* belongs to a class that is reflected as a {@code Class} object

* that is shared by all arrays with the same element type and number

* of dimensions.  The primitive Java types ({@code boolean},

* {@code byte}, {@code char}, {@code short},

* {@code int}, {@code long}, {@code float}, and

* {@code double}), and the keyword {@code void} are also

* represented as {@code Class} objects.

*/

 
通过注释可以看到,主要有这么几类。

接口, 枚举,注解,数组,java基本类型 都可以通过Class 间接得到。


   /*

     * Constructor. Only the Java Virtual Machine creates Class

     * objects.

     */

    private Class() {}

 
也就是说一般不能人为的实例化Class实例。

   public String toString() {
        return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
            + getName();
    }

 

toString 方法:

返回值:interface, class 或者是空串“”。java基本类型 返回值只有类型,不存在具体包名。




  public static Class<?> forName(String className)
                throws ClassNotFoundException {
        return forName0(className, true, ClassLoader.getCallerClassLoader());
    }

 
用于实例化某个JVM上的Class,ClassLoader.getCallerClassLoader() 返回调用该方法的ClassLoader。


在看看它的重载方法:


 public static Class<?> forName(String name, boolean initialize,
                                   ClassLoader loader)
        throws ClassNotFoundException
    {
        if (loader == null) {
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                ClassLoader ccl = ClassLoader.getCallerClassLoader();
                if (ccl != null) {
                    sm.checkPermission(
                        SecurityConstants.GET_CLASSLOADER_PERMISSION);
                }
            }
        }
        return forName0(name, initialize, loader);
    }

 
只是增加了security 检查,以及设置initialize 参数的能力。


这两个方法最终都调用了一个native 方法

  private static native Class<?> forName0(String name, boolean initialize,
                                            ClassLoader loader)
        throws ClassNotFoundException;

 
在看看newInstate 方法

 

 

  public T newInstance()
        throws InstantiationException, IllegalAccessException
    {// 检查该构造方法是不是public的, 如果是就直接调用newInstance0
        if (System.getSecurityManager() != null) {
            checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
        }
        return newInstance0();
    }

 

 private T newInstance0()
        throws InstantiationException, IllegalAccessException
    {
        // NOTE: the following code may not be strictly correct under
        // the current Java memory model.

        // Constructor lookup 检查该类不是Class 类,因为Class类只能有JVM实例化。
        if (cachedConstructor == null) {
            if (this == Class.class) {
                throw new IllegalAccessException(
                    "Can not call newInstance() on the Class for java.lang.Class"
                );
            }
            try {
  //设置构造方法的参数为空数组,这就是而为什么用newInstance实例化类需要有一个为空的构造方法的原因。
                Class<?>[] empty = {};
                //获取构造参数为空的,构造方法
                final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
                 //下面都是做一些security 检查和access设置
                // Disable accessibility checks on the constructor
                // since we have to do the security check here anyway
                // (the stack depth is wrong for the Constructor's
                // security check to work)
                java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction<Void>() {
                        public Void run() {
                                c.setAccessible(true);
                                return null;
                            }
                        });
                cachedConstructor = c;
            } catch (NoSuchMethodException e) {
                throw new InstantiationException(getName());
            }
        }
        Constructor<T> tmpConstructor = cachedConstructor;
        // Security check (same as in java.lang.reflect.Constructor)
        int modifiers = tmpConstructor.getModifiers();
        if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
            Class<?> caller = Reflection.getCallerClass(3);
            if (newInstanceCallerCache != caller) {
                Reflection.ensureMemberAccess(caller, this, null, modifiers);
                newInstanceCallerCache = caller;
            }
        }
        // Run constructor
        try {//实例化相应的独享
            return tmpConstructor.newInstance((Object[])null);
        } catch (InvocationTargetException e) {
            Unsafe.getUnsafe().throwException(e.getTargetException());
            // Not reached
            return null;
        }
    }

 

/**
     * Determines if the specified {@code Object} is assignment-compatible
     * with the object represented by this {@code Class}.  This method is
     * the dynamic equivalent of the Java language {@code instanceof}
     * operator. The method returns {@code true} if the specified
     * {@code Object} argument is non-null and can be cast to the
     * reference type represented by this {@code Class} object without
     * raising a {@code ClassCastException.} It returns {@code false}
     * otherwise.
     ....
     */
    public native boolean isInstance(Object obj);

 

 

 

 

 

 isInstance 方法,通过注释可以知道该方法主要用于判断:参数obj 是否与调用者Class(某个类对应的Class)兼容。 简单一点的就是说 参数obj 能否 Cast  为调用者对应的类。

 

自身类.class.isInstance(自身实例或子类实例)  返回true

String s = new String("test");

System.out.println(Object.class.isInstance(s)); //true

String 可以cast 为object。

 /**
     * Determines if the class or interface represented by this
     * {@code Class} object is either the same as, or is a superclass or
     * superinterface of, the class or interface represented by the specified
     * {@code Class} parameter. It returns {@code true} if so;
     * otherwise it returns {@code false}. If this {@code Class}
     * object represents a primitive type, this method returns
     * {@code true} if the specified {@code Class} parameter is
     * exactly this {@code Class} object; otherwise it returns
     * {@code false}.
     *
   ...
     */
    public native boolean isAssignableFrom(Class<?> cls);

 

isAssignableFrom 与isInstance 方法类似只是参数不同。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics