獲取class對象的三種方式
//Object類的getClass()方法
class c1 = 對象名.getClass();
//類的靜態屬性
Class c2 = 類名.class;
//class類的靜態方法
Class c3 = Class.forName("類的正名");
正名:報名+類名
Student student = new Student();
Class class1 = student.getClass();
Class class2 = Student.class;
Class class3 = Class.forName("reflect.Student");
System.out.println(class1 == class2 );
System.out.println(class1 == class3);
反射方式獲取構造方法
1、獲取對應類的字節碼文件對象
2、根據字節碼文件對象獲取構造器對象
3、通過newInstance方法創建對象
Constructor<T> 構造器對象,屬於java.base模塊,java.lang.reflect包
getConstructor(class<?>...parameterTypes) 只會返回公共構造方法
getDeclaredConstructor(Class<?>...parameterTypes) 可獲取私有構造方法
getConstructors() 返回此類(不含私有)構造方法的數組
常用方法
String getName() 返回構造方法名稱
T newInstance(Object...initargs) 使用此構造方法和指定參數創建並初始化對象
Class class1 =Class.forName("reflect.Student");
Constructor conl = class1.getConstructor();
System.out.println(conl);
Constructor con2 = class1.getConstructor(String.class);
System.out.println(con2.getName());
Student student =(Student) con2.newInstance("尼古拉斯趙四");
System.out.println(student);
Constructor con3 = class1.getDeclaredConstructor(int.class);
System.out.println(con3);
System.out.println("============================");
Constructor[] cons = class1.getConstructors();
for (Constructor constructor : cons) {
System.out.println(constructor);
}
反射方法獲取成員方法並使用
Method對象 方法對象,java.lang.reflect
通過Class 對象獲取方法
getMethod(String name,Class<?>...parameterTypes) 返回一個Method對象,僅公共成員方法
name:方法名稱 parameterTypes:方法的參數列表
getDeclaredMethod(String,Class<?>...)
返回一個Method對象,可獲取私有成員方法
Method的常用方法
String getName() 返回方法名稱
Object invoke(Object obj,Object...args) 在指定對象上調用此方法,參數爲args