2222 */
2323
2424/**
25- * @author Jeff Lee
25+ * @author Jeff
2626 * @since 2015-11-9 10:45:19
27+ * getFields():获得某个类的所有的公共(public)的字段,包括父类中的字段。
28+ * getDeclaredFields():获得某个类的所有声明的字段,
29+ * 即包括public、private和proteced,但是不包括父类的申明字段。
30+ * 同样类似的还有
31+ * getConstructors()和getDeclaredConstructors()、
32+ * getMethods()和getDeclaredMethods(),
33+ * 这两者分别表示获取某个类的方法、构造函数。
2734 * 反射对象构造函数、方法及字段
2835 */
2936public class ReflectionTest {
3037 public final int AGE = 1 ;
3138 public static void main (String [] args ) {
3239 Class cl = null ;
3340 try {
34- cl = Class .forName ("org.javacore.reflection.ReflectionTest" );
41+ // cl = Class.forName("org.javacore.reflection.ReflectionTest");
42+ cl = Class .forName ("org.javacore.reflection.User" );
3543 System .out .println ("打印析构函数:" );
3644 printConstructors (cl );
3745 System .out .println ("打印方法:" );
@@ -51,8 +59,9 @@ public static void printConstructors(Class cl){
5159 // 返回类所有的析构方法
5260 Constructor [] constructors = cl .getDeclaredConstructors ();
5361 for (Constructor c : constructors ){
54- // 返回析构方法名称
62+ // 返回析构方法名称,即是类名 org.javacore.reflection.User
5563 String name = c .getName ();
64+ System .out .print ("name " + name );
5665 System .out .print (" " );
5766 // 获取Java语言的修饰符
5867 // 修饰符由 Java 虚拟机的 public、protected、private、
@@ -83,8 +92,9 @@ public static void printMethods(Class cl){
8392 for (Method m : methods ) {
8493 // 获取方法返回对象
8594 Class retType = m .getReturnType ();
95+ // 获取方法名
8696 String name = m .getName ();
87-
97+ System . out . print ( "name " + name );
8898 System .out .print (" " );
8999 // 获取Java语言的修饰符
90100 // 修饰符由 Java 虚拟机的 public、protected、private、
@@ -105,9 +115,10 @@ public static void printMethods(Class cl){
105115 }
106116 }
107117
108- public static void printFields (Class clazz ){
118+ public static void printFields (Class cl ){
109119 // 获取字段Field对象数组
110- Field [] fields = clazz .getFields ();
120+ Field [] fields = cl .getFields ();
121+ // Field[] fields = cl.getDeclaredFields();
111122 for (Field field : fields ){
112123 // 获取字段声明类型对象
113124 Class type = field .getType ();
@@ -121,7 +132,7 @@ public static void printFields(Class clazz){
121132 String modifiers = Modifier .toString (field .getModifiers ());
122133 if (modifiers .length () > 0 )
123134 System .out .print (modifiers + " " );
124- System .out .print (type .getName () + " " + name );
135+ System .out .println (type .getName () + " " + name );
125136 }
126137 }
127138}
0 commit comments