Class類:
程序運行時,Java運行時系統維護了一份所有對象的運行時類型識別。保持了每個對象的類的信息。虛擬機根據運行時類別信息,選擇正確的方法來執行。
For example, the statement
我們也可以使用一個特殊的Java類來獲得這些信息。這個類就是Class類。對一個對象使用getClass()方法可以獲得Class類型的一個實例。例如:
Employee e;
Class cl = e.getClass();
正如一個Employee對象描述了一個特定的雇員的信息一樣,一個Class對象描述了一個特定的Class的信息。Class類最有用的方法大概是getName(),此方法返回了對象的類名。
例如,如果e是一個Employee類對象,語句:
System.out.println(e.getClass().getName() + " " + e.getName());
打印出:
Employee Harry Hacker
還可以使用靜態方法forName(),通過一個字符串來獲得類對象。
String className = "java.util.Date";
Class cl = Class.forName(className);
如果類名保存在一個字符串中可以使用forName方法來獲得Class對象,這在className是一個類或者接口的名稱時,會起作用。否則,會拋出異常。
TIP
當啟動時,包含main方法的類被加載。并加載它所需要的所有的類,這些類又加載它們用到的類,依此類推。這樣一個大應用程序可能會花費較長的時間,使用戶感到不快。可以采用下面的方法,給用戶程序更快的啟動的錯覺。確保main方法沒有顯式的引用其它類。然后通過調用Class.forName來強制加載其他類。
第三種獲得類對象的方法,如果T是一個java類,T.class返回匹配的類對象。例如:
Class cl1 = Date.class; // if you import java.util.*;
Class cl2 = int.class;
Class cl3 = Double[].class;
Class對象描述了一個類型,這個類型也可能不是一個類。例如,int不是一個類,int.class仍然是一個Class類型的對象。
使用Class對象的newInstance()方法,可以獲得一個對象的實例。例如:
String s = "java.util.Date";
Object m = Class.forName(s).newInstance();
newInstance使用默認的構造函數,如果沒有默認構造函數,會拋出異常。
Using Reflection to Analyze the Capabilities of Classes
Here is a brief overview of the most important parts of the reflection mechanism for letting you examine the structure of a class.
API
java.lang.Class 1.0
static Class forName(String className)
returns the Class object representing the class with name className.
Object newInstance()
returns a new instance of this class.
java.lang.reflect.Constructor 1.1
Object newInstance(Object[] args)
constructs a new instance of the constructor's declaring class.
Parameters:
?args
?the parameters supplied to the constructor. See the section on reflection for more information on how to supply parameters.
java.lang.Throwable 1.0
void printStackTrace()
prints the Throwable object and the stack trace to the standard error stream.
?
使用反射來分析類
Here is a brief overview of the most important parts of the reflection mechanism for letting you examine the structure of a class.
這兒是簡要的介紹反射機制最重要的部分,使用它們可以考查一個類的結構。
All you have to do is have the appropriate method in the Modifier class work on the integer that getModifiers returns. You can also use the Modifier.toString method to print the modifiers.
java.lang.reflect包中Field,Method和Constructor這3個類,分別用來描述一個類的Field,Method和Constructor。這3個類都有一個名為getName的方法,用來獲得項目的名字。Field類有個getType()方法,又返回一個Class對象,描述這個字段的類型。Method和Constructor類都有獲得參數類型的方法,Method類得到了返回類型。3個類都有返回類型為Integer的getModifiers方法,獲得修飾,例如public或者static等。還可以使用java.lang.reflect包中的Modifier類來分析getModifiers的Integer類型返回值。使用Modifier類的isPublic,isPrivate,isFinal方法來獲知一個方法或者構造函數是否是public, private, or final。你所需要做的是使用合適的方法對getModifiers返回的整型值進行操作。也可以使用Modifier.toString()方法來打印修飾符。
Class類的getFields, getMethods, getConstructors方法獲得公共fields,methods和constructors的數組。也包含了超類的公共成員。getdeclaredFields,geTDeclaredMethods和geTDeclaredConstructors方法可以獲得Class類中聲明的所有的fields,方法和構造函數。包含了private和protected成員,但是不包含超類中的成員。
例子5-5顯示了如何打印出一個類的所有信息。這個程序提示你輸入一個類名,打印出所有的數據成員,方法和構造函數。例如,你輸入:
java.lang.Double
程序打印出:
class java.lang.Double extends java.lang.Number
{
?? public java.lang.Double(java.lang.String);
?? public java.lang.Double(double);
?? public int hashCode();
?? public int compareTo(java.lang.Object);
?? public int compareTo(java.lang.Double);
?? public boolean equals(java.lang.Object);
?? public java.lang.String toString();
?? public static java.lang.String toString(double);
?? public static java.lang.Double valueOf(java.lang.String);
?? public static boolean isNaN(double);
?? public boolean isNaN();
?? public static boolean isInfinite(double);
?? public boolean isInfinite();
?? public byte byteValue();
?? public short shortValue();
?? public int intValue();
?? public long longValue();
?? public float floatValue();
?? public double doubleValue();
?? public static double parseDouble(java.lang.String);
?? public static native long doubleToLongBits(double);
?? public static native long doubleToRawLongBits(double);
?? public static native double longBitsToDouble(long);
?? public static final double POSITIVE_INFINITY;
?? public static final double NEGATIVE_INFINITY;
?? public static final double NaN;
?? public static final double MAX_VALUE;
?? public static final double MIN_VALUE;
?? public static final java.lang.Class TYPE;
?? private double value;
?? private static final long serialVersionUID;
}
這個程序可以分析任何java解釋器可以加載的類,而不僅僅是程序編譯時的類。
Example 5-5. ReflectionTest.java
import
?java.util.
*
;
import
?java.lang.reflect.
*
;
public
?
class
?ReflectionTest?{
????
public
?
static
?
void
?main(String[]?args)?{
????????
//
?read?class?name?from?command-line?args?or?user?input
????????String?name;
????????
if
?(args.length?
>
?
0
)
????????????name?
=
?args[
0
];
????????
else
?{
????????????Scanner?in?
=
?
new
?Scanner(System.in);
????????????System.out.println(
"
Enter?class?name?(e.g.?java.util.Date):?
"
);
????????????name?
=
?in.next();
????????}
????????
try
?{
????????????
//
?print?class?name?and?superclass?name?(if?!=?Object)
????????????Class?cl?
=
?Class.forName(name);
????????????Class?supercl?
=
?cl.getSuperclass();
????????????System.out.print(
"
class?
"
?
+
?name);
????????????
if
?(supercl?
!=
?
null
?
&&
?supercl?
!=
?Object.
class
)
????????????????System.out.print(
"
?extends?
"
?
+
?supercl.getName());
????????????System.out.print(
"
\n{\n
"
);
????????????printConstructors(cl);
????????????System.out.println();
????????????printMethods(cl);
????????????System.out.println();
????????????printFields(cl);
????????????System.out.println(
"
}
"
);
????????}?
catch
?(ClassNotFoundException?e)?{
????????????e.printStackTrace();
????????}
????????System.exit(
0
);
????}
????
/**
?????*?Prints?all?constructors?of?a?class
?????*?
?????*?
@param
?cl
?????*????????????a?class
?????
*/
????
public
?
static
?
void
?printConstructors(Class?cl)
?????{
????????Constructor[]?constructors?
=
?cl.getDeclaredConstructors();
?
????????
for
?(Constructor?c?:?constructors)
????????{
???????????String?name?
=
?c.getName();
???????????System.out.print(
"
???
"
?
+
?Modifier.toString(c.getModifiers()));
???????????System.out.print(
"
?
"
?
+
?name?
+
?
"
(
"
);
?
???????????
//
?print?parameter?types
???????????Class[]?paramTypes?
=
?c.getParameterTypes();
???????????
for
?(
int
?j?
=
?
0
;?j?
<
?paramTypes.length;?j
++
)
???????????{
??????????????
if
?(j?
>
?
0
)?System.out.print(
"
,?
"
);
??????????????System.out.print(paramTypes[j].getName());
???????????}
???????????System.out.println(
"
);
"
);
????????}
?????}
????
/**
?????*?Prints?all?methods?of?a?class
?????*?
?????*?
@param
?cl
?????*????????????a?class
?????
*/
????
public
?
static
?
void
?printMethods(Class?cl)
?????{
????????Method[]?methods?
=
?cl.getDeclaredMethods();
?
????????
for
?(Method?m?:?methods)
????????{
???????????Class?retType?
=
?m.getReturnType();
???????????String?name?
=
?m.getName();
?
???????????
//
?print?modifiers,?return?type?and?method?name
???????????System.out.print(
"
???
"
?
+
?Modifier.toString(m.getModifiers()));
???????????System.out.print(
"
?
"
?
+
?retType.getName()?
+
?
"
?
"
?
+
?name?
+
?
"
(
"
);
?
???????????
//
?print?parameter?types
???????????Class[]?paramTypes?
=
?m.getParameterTypes();
???????????
for
?(
int
?j?
=
?
0
;?j?
<
?paramTypes.length;?j
++
)
???????????{
??????????????
if
?(j?
>
?
0
)?System.out.print(
"
,?
"
);
??????????????System.out.print(paramTypes[j].getName());
???????????}
???????????System.out.println(
"
);
"
);
????????}
?????}
????
/**
?????*?Prints?all?fields?of?a?class
?????*?
?????*?
@param
?cl
?????*????????????a?class
?????
*/
????
public
?
static
?
void
?printFields(Class?cl)
?????{
????????Field[]?fields?
=
?cl.getDeclaredFields();
???????
for
?(Field?f?:?fields)
???????{
??????????Class?type?
=
?f.getType();
??????????String?name?
=
?f.getName();
??????????System.out.print(
"
???
"
?
+
?Modifier.toString(f.getModifiers()));
??????????System.out.println(
"
?
"
?
+
?type.getName()?
+
?
"
?
"
?
+
?name?
+
?
"
;
"
);
???????}
????}
}
API
java.lang.Class 1.0
Field[] getFields() 1.1
Field[] getDeclaredFields() 1.1
The getFields method returns an array containing Field objects for the public fields of this class or its superclasses. The geTDeclaredField method returns an array of Field objects for all fields of this class. The methods return an array of length 0 if there are no such fields or if the Class object represents a primitive or array type.
Method[] getMethods() 1.1
Method[] getDeclaredMethods() 1.1
return an array containing Method objects: getMethods returns public methods and includes inherited methods; getdeclaredMethods returns all methods of this class or interface but does not include inherited methods.
Constructor[] getConstructors() 1.1
Constructor[] getDeclaredConstructors() 1.1
return an array containing Constructor objects that give you all the public constructors (for getConstructors) or all constructors (for getdeclaredConstructors) of the class represented by this Class object.
java.lang.reflect.Field 1.1
java.lang.reflect.Method 1.1
java.lang.reflect.Constructor 1.1
Class getDeclaringClass()
returns the Class object for the class that defines this constructor, method, or field.
Class[] getExceptionTypes() (in Constructor and Method classes)
returns an array of Class objects that represent the types of the exceptions thrown by the method.
int getModifiers()
returns an integer that describes the modifiers of this constructor, method, or field. Use the methods in the Modifier class to analyze the return value.
String getName()
returns a string that is the name of the constructor, method, or field.
Class[] getParameterTypes() (in Constructor and Method classes)
returns an array of Class objects that represent the types of the parameters.
Class getReturnType() (in Method classes)
returns a Class object that represents the return type.
java.lang.reflect.Modifier 1.1
static String toString(int modifiers)
returns a string with the modifiers that correspond to the bits set in modifiers.
static boolean isAbstract(int modifiers)
static boolean isFinal(int modifiers)
static boolean isInterface(int modifiers)
static boolean isNative(int modifiers)
static boolean isPrivate(int modifiers)
static boolean isProtected(int modifiers)
static boolean isPublic(int modifiers)
static boolean isStatic(int modifiers)
static boolean isStrict(int modifiers)
static boolean isSynchronized(int modifiers)
static boolean isVolatile(int modifiers)
These methods test the bit in the modifiers value that corresponds to the modifier in the method name.
使用Reflection在運行時分析對象