在前面我们将类的加载的时候,类加载一共有5步,加载,验证,准备,解析和初始化。其中加载阶段,除了将字节码加载到方法区,还生成了这个了的Java.lang.Class对象。那么这个Class对象到底有什么用呢?
前面的关于反射的文章,我们多次都用到了Class类,可以用这个类创建对应类的实例对象,这可以看做是Class类的一个作用。但是这个Class类和对应类本身又有什么联系和区别呢?比如new A()和A.class.newInstance(),联系和区别?
1.什么是Class类&Class类的作用
Class类说变了也是一个类,只不过是一个比较特殊的类。特殊在哪里呢?特殊在这是一个在类加载过程中由虚拟机生成的,由于表示被加载类的类型信息的对象。简单地说,我们创建一个int变量,那么这个int变量是个整数类型,那么我们怎么知道这个类型是整数类型呢?就是通过这个Class类来直到的。
java是面向对象编程的,java中几乎所有的数据都是对象,那么是对象,就必须知道自己到底是哪一种类型的对象。于是Class类便顺势而生了。
Class类的作用放在这边讲有点不太合适,要想了解Class类的作用建议读完下面的内容。我自己理解的话,Class类的作用,本质上讲,就是前面所说的,它代表着一个类的类型信息。正是因为这个特殊作用的存在,Class类能够实现它所代表的这个类的所有功能,包括创建这个类的实例,获得所有的构造函数,方法,字段值等等,可以说无所不能。
2.Class类里面存储了什么
既然我们知道Class类是表示类型的一个特殊的类,那么它是怎么表示某个类或者对象的类型呢?或者说,它里面存储了什么呢?通过反射机制我们知道,Class里面存储了对应类的几乎所有的信息,当然这些信息是未初始化的信息,比如所有的方法,所有的构造函数,所有的字段(成员属性)等等。
那这些信息是怎么存储进去的呢?好吧,这个应该去深入的参考java虚拟机规范吧,毕竟Class这个类的构造函数是私有的,可能是底层的C++代码实现的。
3.class类的静态方法forName()
Modifier and Type | Method and Description |
---|---|
<U> Class<? extends U> | asSubclass(Class<U> clazz) Casts this |
T | cast(Object obj) Casts an object to the class or interface represented by this |
boolean | desiredAssertionStatus() Returns the assertion status that would be assigned to this class if it were to be initialized at the time this method is invoked. |
static Class<?> | forName(String className) Returns the |
static Class<?> | forName(String name, boolean initialize, ClassLoader loader) Returns the |
上述两个方法摘自javadoc,详细的内容可以去javadoc看。最常用的是第一个,注意这个className一定是全限定名,而不能是简单名称。也就是包名.类名
4.class类的所有方法(包括静态方法)
Modifier and Type | Method and Description |
---|---|
<U> Class<? extends U> | asSubclass(Class<U> clazz) Casts this |
T | cast(Object obj) Casts an object to the class or interface represented by this |
boolean | desiredAssertionStatus() Returns the assertion status that would be assigned to this class if it were to be initialized at the time this method is invoked. |
static Class<?> | forName(String className) Returns the |
static Class<?> | forName(String name, boolean initialize, ClassLoader loader) Returns the |
AnnotatedType[] | getAnnotatedInterfaces() Returns an array of |
AnnotatedType | getAnnotatedSuperclass() Returns an |
<A extendsAnnotation> | getAnnotation(Class<A> annotationClass) Returns this element's annotation for the specified type if such an annotation is present, else null. |
Annotation[] | getAnnotations() Returns annotations that are present on this element. |
<A extendsAnnotation> | getAnnotationsByType(Class<A> annotationClass) Returns annotations that are associated with this element. |
String | getCanonicalName() Returns the canonical name of the underlying class as defined by the Java Language Specification. |
Class<?>[] | getClasses() Returns an array containing |
ClassLoader | getClassLoader() Returns the class loader for the class. |
Class<?> | getComponentType() Returns the |
Constructor<T> | getConstructor(Class<?>... parameterTypes) Returns a |
Constructor<?>[] | getConstructors() Returns an array containing |
<A extendsAnnotation> | getDeclaredAnnotation(Class<A> annotationClass) Returns this element's annotation for the specified type if such an annotation is directly present, else null. |
Annotation[] | getDeclaredAnnotations() Returns annotations that are directly present on this element. |
<A extendsAnnotation> | getDeclaredAnnotationsByType(Class<A> annotationClass) Returns this element's annotation(s) for the specified type if such annotations are either directly present or indirectly present. |
Class<?>[] | getDeclaredClasses() Returns an array of |
Constructor<T> | getDeclaredConstructor(Class<?>... parameterTypes) Returns a |
Constructor<?>[] | getDeclaredConstructors() Returns an array of |
Field | getDeclaredField(String name) Returns a |
Field[] | getDeclaredFields() Returns an array of |
Method | getDeclaredMethod(String name, Class<?>... parameterTypes) Returns a |
Method[] | getDeclaredMethods() Returns an array containing |
Class<?> | getDeclaringClass() If the class or interface represented by this |
Class<?> | getEnclosingClass() Returns the immediately enclosing class of the underlying class. |
Constructor<?> | getEnclosingConstructor() If this |
Method | getEnclosingMethod() If this |
T[] | getEnumConstants() Returns the elements of this enum class or null if this Class object does not represent an enum type. |
Field | getField(String name) Returns a |
Field[] | getFields() Returns an array containing |
Type[] | getGenericInterfaces() Returns the |
Type | getGenericSuperclass() Returns the |
Class<?>[] | getInterfaces() Determines the interfaces implemented by the class or interface represented by this object. |
Method | getMethod(String name, Class<?>... parameterTypes) Returns a |
Method[] | getMethods() Returns an array containing |
int | getModifiers() Returns the Java language modifiers for this class or interface, encoded in an integer. |
String | getName() Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this |
Package | getPackage() Gets the package for this class. |
ProtectionDomain | getProtectionDomain() Returns the |
URL | getResource(String name) Finds a resource with a given name. |
InputStream | getResourceAsStream(String name) Finds a resource with a given name. |
Object[] | getSigners() Gets the signers of this class. |
String | getSimpleName() Returns the simple name of the underlying class as given in the source code. |
Class<? super T> | getSuperclass() Returns the |
String | getTypeName() Return an informative string for the name of this type. |
TypeVariable<Class<T>>[] | getTypeParameters() Returns an array of |
boolean | isAnnotation() Returns true if this |
boolean | isAnnotationPresent(Class<? extends Annotation> annotationClass) Returns true if an annotation for the specified type is present on this element, else false. |
boolean | isAnonymousClass() Returns |
boolean | isArray() Determines if this |
boolean | isAssignableFrom(Class<?> cls) Determines if the class or interface represented by this |
boolean | isEnum() Returns true if and only if this class was declared as an enum in the source code. |
boolean | isInstance(Object obj) Determines if the specified |
boolean | isInterface() Determines if the specified |
boolean | isLocalClass() Returns |
boolean | isMemberClass() Returns |
boolean | isPrimitive() Determines if the specified |
boolean | isSynthetic() Returns |
T | newInstance() Creates a new instance of the class represented by this |
String | toGenericString() Returns a string describing this |
String | toString() Converts the object to a string. |
顺便说一下这里的newInstace()方法,因为这个方法比较常用,但是这个会调用对应类的默认无参数构造函数,如果要使用调用有参数的构造器创建一个对象,那么,就必须获得这个构造器,然后再使用构造器调用了。具体的方式向下面这样
//假设A的含参构造器含有4个参数,分别是int,int,string,和类B
Constructor cons = A.class.getConstructor(int.class, int.class, String.class, B.class);
B b = new B();
//获得A的实例。
A a = cons.newInstance(5,5,"Jack",b);