反射(Reflection)能夠讓運(yùn)行于 JVM 中的程序檢測(cè)和修改運(yùn)行時(shí)的行為。
Class類提供了以下方法
- 四個(gè)public方法未檩,用于獲取某個(gè)類的構(gòu)造方法:
Constructor getConstructor(Class[] params)
// 根據(jù)構(gòu)造函數(shù)的參數(shù)戴尸,返回一個(gè)具體的具有public屬性的構(gòu)造函數(shù)
Constructor getConstructors()
// 返回所有具有public屬性的構(gòu)造函數(shù)數(shù)組
Constructor getDeclaredConstructor(Class[] params)
// 根據(jù)構(gòu)造函數(shù)的參數(shù),返回一個(gè)具體的構(gòu)造函數(shù)(不分public和非public屬性)
Constructor getDeclaredConstructors()
// 返回該類中所有的構(gòu)造函數(shù)數(shù)組(不分public和非public屬性)
- 四種獲取成員方法的方法
Method getMethod(String name, Class[] params)
// 根據(jù)方法名和參數(shù)冤狡,返回一個(gè)具體的具有public屬性的方法
Method[] getMethods()
// 返回所有具有public屬性的方法數(shù)組
Method getDeclaredMethod(String name, Class[] params)
// 根據(jù)方法名和參數(shù)孙蒙,返回一個(gè)具體的方法(不分public和非public屬性)
Method[] getDeclaredMethods()
// 返回該類中的所有的方法數(shù)組(不分public和非public屬性)
- 四種獲取成員屬性的方法
Field getField(String name)
// 根據(jù)變量名,返回一個(gè)具體的具有public屬性的成員變量
Field[] getFields()
// 返回具有public屬性的成員變量的數(shù)組
Field getDeclaredField(String name)
// 根據(jù)變量名悲雳,返回一個(gè)成員變量(不分public和非public屬性)
Field[] getDelcaredFields()
// 返回所有成員變量組成的數(shù)組(不分public和非public屬性)
getDeclaredFields 和 getFields 的區(qū)別:
getDeclaredFields()獲得某個(gè)類的所有申明的字段挎峦,即包括public、private和proteced合瓢,但是不包括父類的申明字段坦胶。
getFields()獲得某個(gè)類的所有的公共(public)的字段,包括父類晴楔。
- 獲取父類的方法
Class<?> superclass = class1.getSuperclass() ;
- 獲取接口
Class<?>[] interS = class1.getInterfaces() ;
// 獲取所有的接口
- 實(shí)例化
Object object = class1.newInstance() ;
//創(chuàng)建實(shí)例化:相當(dāng)于 new 了一個(gè)對(duì)象
實(shí)例
Person.class
package reflection;
public class Person {
private String id;
private String name;
public String age;
public static String str = "Json";
//構(gòu)造函數(shù)1
public Person() {
System.out.println( "構(gòu)造函數(shù) 無(wú)參" );
}
//構(gòu)造函數(shù)2
public Person(String id) {
this.id = id;
System.out.println( "構(gòu)造函數(shù) id : " + id );
}
//構(gòu)造函數(shù)3
public Person(String id, String name) {
this.id = id;
this.name = name;
System.out.println( "構(gòu)造函數(shù) id : " + id + " name: " + name );
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
/**
* 靜態(tài)方法
*/
public static String update(int id) {
return str+id;
}
}
練習(xí)一:通過(guò)反射顿苇,獲取對(duì)象實(shí)例,并且操作對(duì)象的方法
package reflection;
public class T1 {
public static void main(String[] args) {
try {
//創(chuàng)建類
Class<?> class1 = Class.forName("reflection.Person");
//創(chuàng)建實(shí)例化:相當(dāng)于 new 了一個(gè)對(duì)象
Object object = class1.newInstance();
//向下轉(zhuǎn)型
Person person = (Person) object;
person.setId("100");
person.setName("jack");
System.out.println("id: " + person.getId() + " name: " + person.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
運(yùn)行結(jié)果:
id: 100 name: jack
練習(xí)二:通過(guò)反射獲取對(duì)象字段屬性税弃,并且賦值
package reflection;
import java.lang.reflect.Field;
public class T1 {
public static void main(String[] args) {
try {
//創(chuàng)建類
Class<?> class1 = Class.forName("reflection.Person");
//創(chuàng)建實(shí)例
Object person = class1.newInstance();
//獲得id 屬性
Field idField = class1.getDeclaredField( "id" ) ;
//打破封裝 實(shí)際上setAccessible是啟用和禁用訪問(wèn)安全檢查的開(kāi)關(guān),并不是為true就能訪問(wèn)為false就不能訪問(wèn)
//由于JDK的安全檢查耗時(shí)較多.所以通過(guò)setAccessible(true)的方式關(guān)閉安全檢查就可以達(dá)到提升反射速度的目的
idField.setAccessible( true );
//給id 屬性賦值
idField.set(person, "100") ;
//打印 person 的屬性值
System.out.println( idField.get( person ));
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace() ;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
id 這個(gè)屬性的是 private 私有的纪岁,不能修改它的值。需要添加 idField.setAccessible( true );
練習(xí)三:通過(guò)反射操作屬性和方法
package reflection;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class T1 {
public static void main(String[] args) {
try {
//創(chuàng)建類
Class<?> class1 = Class.forName("reflection.Person");
//創(chuàng)建實(shí)例
Object person = class1.newInstance();
//獲得id 屬性
Field idField = class1.getDeclaredField( "id" ) ;
//打破封裝 實(shí)際上setAccessible是啟用和禁用訪問(wèn)安全檢查的開(kāi)關(guān),并不是為true就能訪問(wèn)為false就不能訪問(wèn)
//由于JDK的安全檢查耗時(shí)較多.所以通過(guò)setAccessible(true)的方式關(guān)閉安全檢查就可以達(dá)到提升反射速度的目的
idField.setAccessible( true );
//給id 屬性賦值
idField.set( person , "100") ;
//獲取 setName() 方法
Method setName = class1.getDeclaredMethod( "setName", String.class ) ;
//打破封裝
setName.setAccessible( true );
//調(diào)用setName 方法则果。
setName.invoke( person , "jack" ) ;
//獲取name 字段
Field nameField = class1.getDeclaredField( "name" ) ;
//打破封裝
nameField.setAccessible( true );
//打印 person 的 id 屬性值
String id_ = (String) idField.get( person ) ;
System.out.println( "id: " + id_ );
//打印 person 的 name 屬性值
String name_ = ( String)nameField.get( person ) ;
System.out.println( "name: " + name_ );
//獲取 getName 方法
Method getName = class1.getDeclaredMethod( "getName" ) ;
//打破封裝
getName.setAccessible( true );
//執(zhí)行g(shù)etName方法幔翰,并且接收返回值
String name_2 = (String) getName.invoke( person ) ;
System.out.println( "name2: " + name_2 );
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace() ;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
運(yùn)行結(jié)果:
id: 100
name: jack
name2: jack
練習(xí)四:靜態(tài)屬性、靜態(tài)方法調(diào)用
package reflection;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class T1 {
public static void main(String[] args) {
try {
//創(chuàng)建類
Class<?> class1 = Class.forName("reflection.Person");
//獲取 nameField 屬性
Field nameField = class1.getDeclaredField( "str" ) ;
//獲取 nameField 的值
String name_ = (String) nameField.get( nameField ) ;
//輸出值
System.out.println( name_ );
//有返回值西壮,有參數(shù)
Method getUpdateMethod = class1.getDeclaredMethod( "update" , int.class ) ;
String result_4 = (String) getUpdateMethod.invoke( null , 1 ) ;
System.out.println( "返回值: "+ result_4 );
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace() ;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
練習(xí)五:調(diào)用構(gòu)造函數(shù)遗增,創(chuàng)建對(duì)象實(shí)例
package reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class T1 {
public static void main(String[] args) {
try {
//創(chuàng)建類
Class<?> class1 = Class.forName("reflection.Person");
//無(wú)參構(gòu)造函數(shù)
Object object = class1.newInstance() ;
//有參構(gòu)造函數(shù):一個(gè)參數(shù)
Constructor<?> constructor = class1.getDeclaredConstructor( String.class ) ;
constructor.newInstance( "1000" ) ;
//有參構(gòu)造函數(shù):二個(gè)參數(shù)
Constructor<?> constructor2 = class1.getDeclaredConstructor( String.class , String.class ) ;
constructor2.newInstance( "1001" , "jack" ) ;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace() ;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}