Java中的java.lang.Class API 詳解
且將新火試新茶,詩酒趁年華。
概述
Class
是一個位於java.lang
包下面的一個類,在Java
中每個類例項都有對應的Class
物件。類物件是由Java虛擬機器(JVM)自動構造的。
Class
類的方法經常在反射時被呼叫。
建立Class物件
有三種方法可以建立Class物件
-
Class.forName(“className”)
:因為Class
類沒有公共的構造方法,所以存在一個靜態的方法返回Class
物件,即Class.forName()
用於建立Class
物件。要建立的Class
物件的類名在執行時確定,不存在則丟擲ClassNotFoundException
。(注意className
為類的完整包名)Class.forName("java.lang.String")
-
Myclass.class
:當我們在類名後面跟上.class
時,就會返回當前類的Class
物件。它主要應用於原始資料型別,並且僅在我們知道類的名稱時才使用。要建立的Class
物件的類名在編譯時確定
Class c2 = String.class;
請注意,此方法與類名一起使用,而不是與類例項一起使用
A a = new A();// Class A 的例項a Class c = A.class; // 正確用法 Class c = a.class; //編譯出錯
-
obj.getClass()
: 此方法存在時Object
類中,它返回此obj
物件的執行時類。String str = new String("string"); Class c3 = str.getClass();
Class物件裡面的方法
String toString()
此方法將Class
物件轉換為字串。它返回字串表示形式,即字串“class”或“interface”,後跟空格,然後是類的含包名名稱。如果Class
物件表示基本型別,則此方法返回基本型別的名稱,如果它表示void
,則返回“void”
描述:
語法 : public String toString() 引數 : NA 返回 : a string representation of this class object. 重寫 : toString in class Object
測試類:
public class ToStringTest { public static void main(String[] args) throws ClassNotFoundException { Class c1 = Class.forName("java.lang.String"); Class c2 = int.class; Class c3 = void.class; System.out.println("Class represented by c1: "+c1.toString()); System.out.println("Class represented by c2: "+c2.toString()); System.out.println("Class represented by c3: "+c3.toString()); } }
輸出:
Class represented by c1: class java.lang.String Class represented by c2: int Class represented by c3: void
String toGenericString()
返回描述此類的字串,包括有關修飾符和型別引數的資訊。
描述:
語法 : public String toGenericString() 引數 : NA 返回 : a string describe of this class object.
測試類:
public class ToGenericStringTest { public static void main(String[] args) throws ClassNotFoundException { Class c1 = Class.forName("java.lang.String"); Class c2 = int.class; Class c3 = void.class; System.out.println("Class represented by c1: "+c1.toGenericString()); System.out.println("Class represented by c2: "+c2.toGenericString()); System.out.println("Class represented by c3: "+c3.toGenericString()); } }
輸出:
Class represented by c1: public final class java.lang.String Class represented by c2: int Class represented by c3: void
Class<?> forName(String className)
返回與給定字串名稱的類或介面相關聯的 類物件。
描述:
語法 : public static Class<?> forName(String className) throws ClassNotFoundException 引數 : className -含包名 返回 : 返回指定包名的class物件 異常: ClassNotFoundException ......
測試類:
public class ToClassForNameTest { public static void main(String[] args) throws ClassNotFoundException { Class c1 = Class.forName("java.lang.String"); } }
輸出:
Class<?> forName(String className,boolean initialize, ClassLoader loader)
使用給定的類載入器返回與給定字串名稱的類或介面相關聯的類物件。如果引數loader為空,則通過引導類載入器載入該類。只有當initialize引數為true並且尚未被初始化時,該類才被初始化。
描述:
語法 : public static Class<?> forName(String className,boolean initialize, ClassLoader loader) throws ClassNotFoundException 引數 : className -含包名 initialize - 如果true該類將被初始化。 loader- 類載入器 返回 : 返回指定包名的class物件 異常: ClassNotFoundException ......
測試類:
public class ToClassForNameTest { public static void main(String[] args) throws ClassNotFoundException { Class myClass = Class.forName("Test"); ClassLoader loader = myClass.getClassLoader(); Class c = Class.forName("java.lang.String",true,loader) } }
輸出:
T newInstance()
此方法建立此Class物件表示的類的新例項。通過具有空引數列表的新表示式建立類。如果尚未初始化,則初始化該類。
描述:
語法 : public T newInstance() throws InstantiationException,IllegalAccessException 引數 : NA 返回 : 由此物件表示的類的新分配例項 異常: IllegalAccessException ......
測試類:
public class NewInstanceTest { public static void main(String[] args) throws ClassNotFoundException { Class c1 = Class.forName("java.lang.String"); Object instance = c1.newInstance(); System.out.println("instance class : " + instance.getClass()); } }
輸出:
instance class : class java.lang.String
boolean isInstance(Object obj)
此方法確定指定的Object是否與此Class表示的物件分配相容。它相當於java
中的instanceof
運算子
描述:
語法 : public boolean isInstance(Object obj) 引數 : obj - the object to check 返回 : true if obj is an instance of this class else return false 異常:
測試類:
public class IsInstanceTest { public static void main(String[] args) throws ClassNotFoundException { Class c = Class.forName("java.lang.String"); String url = "http://niocoder.com"; int i = 10; boolean b1 = c.isInstance(url); boolean b2 = c.isInstance(i); System.out.println("is url instance of String : " + b1); System.out.println("is i instance of String : " + b2); } }
輸出:
is url instance of String : true is i instance of String : false
boolean isAssignableFrom(Class<?> cls)
此方法確定此Class物件表示的類或介面是否與指定的Class引數表示的類或介面相同,或者是超類或超介面。
描述:
語法 : public boolean isAssignableFrom(Class<?> cls) 引數 : cls - the Class object to be checked 返回 : true if objects of the type cls can be assigned to objects of this class
測試類:
public class IsAssignableFrom extends Thread { public static void main(String[] args) throws Exception { Class myClass = Class.forName("com.niocoder.test.java.method.IsAssignableFrom"); Class c1 = Class.forName("java.lang.Thread"); Class c2 = Class.forName("java.lang.String"); boolean b1 = c1.isAssignableFrom(myClass); boolean b2 = c2.isAssignableFrom(myClass); System.out.println("is Thread class Assignable from IsAssignableFrom : " + b1); System.out.println("is String class Assignable from Test : " + b2); } }
輸出:
is Thread class Assignable from IsAssignableFrom : true is String class Assignable from Test : false
boolean isInterface()
此方法確定指定的Class
物件是否表示介面型別
描述:
語法 : public boolean isInterface() 引數 : NA 返回 : return true if and only if this class represents an interface type else return false
測試類:
public class IsInterfaceTest { public static void main(String[] args) throws Exception { Class c1 = Class.forName("java.lang.String"); Class c2 = Class.forName("java.lang.Runnable"); boolean b1 = c1.isInterface(); boolean b2 = c2.isInterface(); System.out.println("is java.lang.String an interface : " + b1); System.out.println("is java.lang.Runnable an interface : " + b2); } }
輸出:
is java.lang.String an interface : false is java.lang.Runnable an interface : true
boolean isPrimitive()
此方法確定指定的Class物件是否表示基本型別。即boolean , byte , char , short , int , long , float和double 。
描述:
語法 : public boolean isPrimitive() 引數 : NA 返回 : return true if and only if this class represents a primitive type else return false
測試類:
public class IsPrimitiveTest { public static void main(String[] args) { Class c1 = int.class; Class c2 = IsPrimitiveTest.class; boolean b1 = c1.isPrimitive(); boolean b2 = c2.isPrimitive(); System.out.println("is " + c1.toString() + " primitive : " + b1); System.out.println("is " + c2.toString() + " primitive : " + b2); } }
輸出:
is int primitive : true is class com.niocoder.test.java.method.IsPrimitiveTest primitive : false
boolean isArray()
此方法確定指定的Class物件是否表示陣列類。
描述:
語法 : public boolean isArray() 引數 : NA 返回 : return true if and only if this class represents an array type else return false
測試類:
public class IsArrayTest { public static void main(String[] args) { int a[] = new int[2]; Class c1 = a.getClass(); Class c2 = IsArrayTest.class; boolean b1 = c1.isArray(); boolean b2 = c2.isArray(); System.out.println("is "+c1.toString()+" an array : " + b1); System.out.println("is "+c2.toString()+" an array : " + b2); } }
輸出:
is class [I an array : true is class com.niocoder.test.java.method.IsArrayTest an array : false
boolean isAnonymousClass()
當且僅當此類是匿名類時,此方法才返回true。匿名類與本地類類似,只是它們沒有名稱
描述:
語法 : public boolean isAnonymousClass() 引數 : NA 返回 : true if and only if this class is an anonymous class.false,otherwise.
boolean isLocalClass()
當且僅當此類是本地類時,此方法才返回true。本地類是在Java程式碼塊中本地宣告的類,而不是類的成員。
描述:
語法 : public boolean isLocalClass() 引數 : NA 返回 : true if and only if this class is a local class.false,otherwise.
boolean isMemberClass()
當且僅當此類是Member類時,此方法返回true。
描述:
語法 : public boolean isMemberClass() 引數 : NA 返回 : true if and only if this class is a Member class.false,otherwise.
boolean isEnum()
當且僅當此類在原始碼中宣告為列舉時,此方法才返回true
描述:
語法 : public boolean isEnum() 引數 : NA 返回 : true iff this class was declared as an enum in the source code.false,otherwise.
boolean isAnnotation()
此方法確定此Class物件是否表示註釋型別。請注意,如果此方法返回true,則isInterface()方法也將返回true,因為所有註釋型別也是介面
描述:
語法 : public boolean isAnnotation() 引數 : NA 返回 : return true if and only if this class represents an annotation type else return false
測試類:
public class IsTest {
@interface B { // Annotation element definitions } //列舉 enum Color { RED, GREEN, BLUE; } //Member class class A { } public static void main(String[] args) { // 匿名類 IsTest t1 = new IsTest() { }; Class c1 = t1.getClass(); Class c2 = IsTest.class; Class c3 = A.class; Class c4 = Color.class; Class c5 = B.class; boolean b1 = c1.isAnonymousClass(); System.out.println("is " + c1.toString() + " an anonymous class : " + b1); boolean b2 = c2.isLocalClass(); System.out.println("is " + c2.toString() + " a local class : " + b2); boolean b3 = c3.isMemberClass(); System.out.println("is " + c3.toString() + " a member class : " + b3); boolean b4 = c4.isEnum(); System.out.println("is " + c3.toString() + " a Enum class : " + b4); boolean b5 = c5.isAnnotation(); System.out.println("is " + c3.toString() + " an annotation: " + b5); } }
輸出:
is class com.niocoder.test.java.method.IsTest$1 an anonymous class : true is class com.niocoder.test.java.method.IsTest a local class : false is class com.niocoder.test.java.method.IsTest$A a member class : true is class com.niocoder.test.java.method.IsTest$A a Enum class : true is class com.niocoder.test.java.method.IsTest$A an annotation: true
String getName()
返回由 類物件表示的實體(類,介面,陣列類,原始型別或空白)的名稱(含包明),作為 String 。
描述:
語法 : public String getName() 引數 : NA 返回 : returns the name of the name of the entity represented by this object.
String getSimpleName()
此方法返回原始碼中給出的基礎類的名稱(不含包名)。如果基礎類是匿名類,則返回空字串
描述:
語法 : public String getSimpleName() 引數 : NA 返回 : the simple name of the underlying class
測試類:
public class GetNameTest { public static void main(String[] args) { Class c = GetNameTest.class; System.out.print("Class Name associated with c : "); System.out.println(c.getName()); System.out.println(c.getSimpleName()); } }
輸出:
Class Name associated with c : com.niocoder.test.java.method.GetNameTest GetNameTest
ClassLoader getClassLoader()
此方法返回此類的類載入器。如果類載入器是bootstrap類載入器,那麼此方法返回null,因為引導類載入器是用C,C ++等本機語言實現的。如果此物件表示基本型別或void,則返回null
描述:
語法 : public ClassLoader getClassLoader() 引數 : NA 返回 : the class loader that loaded the class or interface represented by this object represented by this object.
TypeVariable<Class>[ ] getTypeParameters()
此方法返回一個TypeVariable物件陣列,該物件表示由此GenericDeclaration物件表示的泛型宣告宣告的型別變數,按宣告順序
描述:
語法 : public TypeVariable<Class<T>>[] getTypeParameters() 引數 : NA 返回 : an array of TypeVariable objects that represent the type variables declared by this generic declaration represented by this object.
測試類:
public class GetClassLoaderTest { public static void main(String[] args) throws Exception { { Class myClass = Class.forName("com.niocoder.test.java.method.GetClassLoaderTest"); Class c1 = Class.forName("java.lang.String"); Class c2 = int.class; System.out.print("GetClassLoaderTest class loader : "); System.out.println(myClass.getClassLoader()); System.out.print("String class loader : "); System.out.println(c1.getClassLoader()); System.out.print("primitive int loader : "); System.out.println(c2.getClassLoader()); } { Class c = Class.forName("java.util.Set"); TypeVariable[] tv = c.getTypeParameters(); System.out.println("TypeVariables in "+c.getName()+" class : "); for (TypeVariable typeVariable : tv) { System.out.println(typeVariable); } } } }
輸出:
GetClassLoaderTest class loader : sun.misc.Launcher$AppClassLoader@18b4aac2 String class loader : null primitive int loader : null TypeVariables in java.util.Set class : E
Class<? super T> getSuperclass()
此方法返回表示此Class所表示的實體(類,介面,基本型別或void)的超類的Class。如果此Class表示Object類,介面,基本型別或void,則返回null。如果此物件表示陣列類,則返回表示Object類的Class物件。
描述:
語法 : public Class<? super T> getSuperclass() 引數 : NA 返回 : the superclass of the class represented by this object
Type getGenericSuperclass()
此方法返回表示此Class所表示的實體(類,介面,基本型別或void)的直接超類的Type。如果此Class表示Object類,介面,基本型別或void,則返回null。如果此物件表示陣列類,則返回表示Object類的Class物件。
描述:
語法 : public Type getGenericSuperclass() 引數 : NA 返回 : athe superclass of the class represented by this object
Class<?>[] getInterfaces()
此方法返回由此物件表示的類或介面實現的介面。如果此物件表示不實現介面的類或介面,則該方法返回長度為0的陣列。如果此物件表示基本型別或void,則該方法返回長度為0的陣列。
描述:
語法 : public Class<?>[] getInterfaces() 引數 : NA 返回 : an array of interfaces implemented by this class.
Package getPackage()
此方法返回此類的包。
描述:
語法 : public Package getPackage() 引數 : NA 返回 : the package of the class, or null if no package information is available from the archive or codebase.
測試類:
public class GetSuperClassTest { public static void main(String[] args) throws Exception { System.out.println("getSuperclass-----------------------------------------"); { Class myClass = GetSuperClassTest.class; Class c1 = Class.forName("com.niocoder.test.java.method.A"); Class c2 = Class.forName("com.niocoder.test.java.method.B"); Class c3 = Class.forName("java.lang.Object"); System.out.print("GetSuperClassTest superclass : "); System.out.println(myClass.getSuperclass()); System.out.print("A superclass : "); System.out.println(c1.getSuperclass()); System.out.print("B superclass : "); System.out.println(c2.getSuperclass()); System.out.print("Object superclass : "); System.out.println(c3.getSuperclass()); } System.out.println("getGenericSuperclass-----------------------------------------"); { Class myClass = GetSuperClassTest.class; Class c1 = Class.forName("java.util.ArrayList"); Class c3 = Class.forName("java.lang.Object"); System.out.print("GetSuperClassTest superclass : "); System.out.println(myClass.getGenericSuperclass()); System.out.print("ArrayList superclass : "); System.out.println(c1.getGenericSuperclass()); System.out.print("Object superclass : "); System.out.println(c3.getGenericSuperclass()); } System.out.println("getInterfaces-----------------------------------------"); { Class c1 = Class.forName("com.niocoder.test.java.method.D"); Class c2 = Class.forName("java.lang.String"); Class c1Interfaces[] = c1.getInterfaces(); Class c2Interfaces[] = c2.getInterfaces(); System.out.println("interfaces implemented by D class : "); for (Class class1 : c1Interfaces) { System.out.println(class1); } System.out.println("interfaces implemented by String class : "); for (Class class1 : c2Interfaces) { System.out.println(class1); } } System.out.println("getPackage-----------------------------------------"); { Class c1 = Class.forName("java.lang.String"); Class c2 = Class.forName("java.util.ArrayList"); System.out.println(c1.getPackage()); System.out.println(c2.getPackage()); } } } class A { } class B extends A { } interface C { } interface D extends C { }
輸出:
getSuperclass----------------------------------------- GetSuperClassTest superclass : class java.lang.Object A superclass : class java.lang.Object B superclass : class com.niocoder.test.java.method.A Object superclass : null getGenericSuperclass----------------------------------------- GetSuperClassTest superclass : class java.lang.Object ArrayList superclass : java.util.AbstractList<E> Object superclass : null getInterfaces----------------------------------------- interfaces implemented by D class : interface com.niocoder.test.java.method.C interfaces implemented by String class : interface java.io.Serializable interface java.lang.Comparable interface java.lang.CharSequence getPackage----------------------------------------- Disconnected from the target VM, address: '127.0.0.1:59273', transport: 'socket' package java.lang, Java Platform API Specification, version 1.8 package java.util, Java Platform API Specification, version 1.8
Field[] getFields()
此方法返回一個Field物件陣列,該物件反映此Class物件表示的類(及其所有超類)或介面(及其所有超類)的所有可訪問公共欄位
描述:
語法 : public Field[] getFields()throws SecurityException 引數 : NA 返回 : the array of Field objects representing the public fields andarray of length 0 if the class or interface has no accessible public fields or if this Class object represents a primitive type or void.
測試類:
public class GetFieldsTest { public static void main(String[] args) throws Exception { Class c1 = Class.forName("java.lang.Integer"); Field F[] = c1.getFields(); System.out.println("Below are the fields of Integer class : "); for (Field field : F) { System.out.println(field); } } }
輸出:
Below are the fields of Integer class : public static final int java.lang.Integer.MIN_VALUE public static final int java.lang.Integer.MAX_VALUE public static final java.lang.Class java.lang.Integer.TYPE public static final int java.lang.Integer.SIZE public static final int java.lang.Integer.BYTES
Method[] getMethods()
此方法返回一個Method物件陣列,這些物件反映了類或介面的所有可訪問的公共方法,以及從此Class物件表示的超類和超級介面繼承的方法。
描述:
語法 : public Method[] getMethods() throws SecurityException 引數 : NA 返回 : the array of Method objects representing the public methods andarray of length 0 if the class or interface has no accessible public method or if this Class object represents a primitive type or void.
測試類:
public class GetMethodsTest { public static void main(String[] args) throws Exception { Class c1 = Class.forName("java.lang.Object"); Method M[] = c1.getMethods(); System.out.println("Below are the methods of Object class : "); for (Method method : M) { System.out.println(method); } } }
輸出:
Below are the methods of Object class : public final void java.lang.Object.wait() throws java.lang.InterruptedException public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException public boolean java.lang.Object.equals(java.lang.Object) public java.lang.String java.lang.Object.toString() public native int java.lang.Object.hashCode() public final native java.lang.Class java.lang.Object.getClass() public final native void java.lang.Object.notify() public final native void java.lang.Object.notifyAll()
Constructor<?>[] getConstructors()
此方法返回一個Constructor物件陣列,這些物件反映此Class物件所表示的類的所有公共建構函式
描述:
語法 : public Constructor<?>[] getConstructors() throws SecurityException 引數 : NA 返回 : the array of Constructor objects representing the public constructors of this class andarray of length 0 if the class or interface has no accessible public constructor or if this Class object represents a primitive type or void.
測試類:
public class GetConstructorsTest { public static void main(String[] args) throws Exception { Class c1 = Class.forName("java.lang.Boolean"); Constructor C[] = c1.getConstructors(); System.out.println("Below are the constructors of Boolean class :"); for (Constructor constructor : C) { System.out.println(constructor); } } }
輸出:
public java.lang.Boolean(boolean) public java.lang.Boolean(java.lang.String)
Field getField(String fieldName)
此方法返回一個Field物件,該物件反映此Class物件所表示的類或介面的指定公共成員欄位
描述:
語法 : public Field getField(String fieldName) throws NoSuchFieldException,SecurityException 引數 : fieldName -the field name 返回 : the Field object of this class specified by name
Method getMethod(String methodName,Class… parameterTypes)
此方法返回一個Method物件,該物件反映此Class物件所表示的類或介面的指定公共成員方法
描述:
語法 : public Method getMethod(String methodName,Class... parameterTypes) throws NoSuchFieldException,SecurityException 引數 : methodName -the method name parameterTypes - the list of parameters 返回 : the method object of this class specified by name
ConstructorgetConstructor(Class… parameterTypes)
此方法返回一個Constructor物件,該物件反映此Class物件所表示的類的指定公共建構函式.parameterTypes引數是一個Class物件的陣列,用於按宣告的順序標識建構函式的形式引數型別
描述:
語法 : public Constructor<?> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException,SecurityException 引數 : parameterTypes - the list of parameters 返回 : the Constructor object of the public constructor that matches the specified parameterTypes
測試類:
public class GetFieldsNameTest { public static void main(String[] args) throws Exception { System.out.println("getField--------------------------------------------"); { Class c1 = Class.forName("java.lang.Integer"); Field f = c1.getField("MIN_VALUE"); System.out.println("public field in Integer class with MIN_VALUE name :"); System.out.println(f); } System.out.println("getMethod--------------------------------------------"); { Class c1 = Class.forName("java.lang.Integer"); Class c2 = Class.forName("java.lang.String"); Method m = c1.getMethod("parseInt", c2); System.out.println("method in Integer class specified by parseInt : "); System.out.println(m); } System.out.println("getConstructor--------------------------------------------"); { Class c1 = Class.forName("java.lang.Integer"); Class c2 = Class.forName("java.lang.String"); Constructor c = c1.getConstructor(c2); System.out.println("Constructor in Integer class & String parameterType:"); System.out.println(c); } } }
輸出:
getField-------------------------------------------- public field in Integer class with MIN_VALUE name : public static final int java.lang.Integer.MIN_VALUE getMethod-------------------------------------------- method in Integer class specified by parseInt : public static int java.lang.Integer.parseInt(java.lang.String) throws java.lang.NumberFormatException getConstructor-------------------------------------------- Constructor in Integer class & String parameterType: public java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException
T cast(Object obj)
此方法用於將物件強制轉換為此Class物件表示的類或介面。
描述:
語法 : public T cast(Object obj) 引數 : obj - the object to be cast 返回 : the object after casting, or null if obj is null
Class<? extends U> asSubclass(Classclazz)
此方法用於轉換此Class物件以表示由指定的類物件表示的類的子類。它始終返回對此類物件的引用
描述:
語法 : public <U> Class<? extends U> asSubclass(Class<U> class) 引數 : clazz - the superclass object to be cast 返回 : this Class object, cast to represent a subclass of the specified class object.
測試類:
public class CastTest { public static void main(String[] args) { { A1 a = new A1(); System.out.println(a.getClass()); B1 b = new B1(); a = A1.class.cast(b); System.out.println(a.getClass()); } { A1 a = new A1(); Class superClass = a.getClass(); B1 b = new B1(); Class subClass = b.getClass(); Class cast = subClass.asSubclass(superClass); System.out.println(cast); } } } class A1 { } class B1 extends A1 { }
輸出:
class com.niocoder.test.java.method.A1 class com.niocoder.test.java.method.B1 class com.niocoder.test.java.method.B1