微信搜索:碼農StayUphtml
主頁地址:gozhuyinglong.github.iojava
源碼分享:github.com/gozhuyinglo…git
在OOP的世界裏,萬物皆對象。也就是說,咱們能夠將任何東西抽象成一個對象。github
好比人,能夠抽象成一個Person類,經過new Person()來實例化一個對象;再好比鴨子,能夠抽象成一個Duck類,也能夠對其進行實例化……那麼這一個個類自己是否是也能夠抽象成一個類呢?Java提供了一個特殊的類Class
,用來描述類的內部信息,是反射的核心類。編程
下圖是本篇講述內容:api
Java反射(Reflection)容許應用程序在運行時藉助於反射API,來獲取全部類或接口的內部信息,而且能直接操做任意對象的內部屬性及方法。反射機制的核心類爲java.lang.Class
。數組
Class
類型的對象。Class
類沒有公開的構造函數,是由類加載器的defineClass
方法構造而成。因此Class
對象不是「new」出來的,而是經過方法來獲取的。Class
對象具備類的完整結構信息,而且一個類只有一個Class
對象。獲取Class
對象有如下四種方式:安全
下面使用代碼展現獲取 Person 類的Class
對象的四種方式:微信
@Test
public void testClassFor() {
// 1.經過類實例獲取
Person person = new Person();
Class<? extends Person> clazz1 = person.getClass();
System.out.println("01 - " + clazz1);
// 2.經過類直接調用class獲取
Class<Person> clazz2 = Person.class;
System.out.println("02 - " + clazz2);
// 3.經過Class.forName獲取
Class<?> clazz3 = null;
try {
clazz3 = Class.forName("io.github.gozhuyinglong.reflection.Person");
} catch (ClassNotFoundException e) {
// 當找不到指定類時,會拋出此異常
e.printStackTrace();
}
System.out.println("03 - " + clazz3);
// 4.經過類加載器獲取
ClassLoader classLoader = this.getClass().getClassLoader();
Class<?> clazz4 = null;
try {
clazz4 = classLoader.loadClass("io.github.gozhuyinglong.reflection.Person");
} catch (ClassNotFoundException e) {
// 當找不到指定類時,會拋出此異常
e.printStackTrace();
}
System.out.println("04 - " + clazz4);
// hashCode相等,說明這四種方式獲取的是同一個實例
System.out.println("05 - " + clazz1.hashCode());
System.out.println("06 - " + clazz2.hashCode());
System.out.println("07 - " + clazz3.hashCode());
System.out.println("08 - " + clazz4.hashCode());
}
複製代碼
輸出結果:markdown
01 - class io.github.gozhuyinglong.reflection.Person
02 - class io.github.gozhuyinglong.reflection.Person
03 - class io.github.gozhuyinglong.reflection.Person
04 - class io.github.gozhuyinglong.reflection.Person
05 - 721748895
06 - 721748895
07 - 721748895
08 - 721748895
複製代碼
經過上面的輸出結果能夠看出,這四個Class
對象的hashCode
相同,說明使用這四種方式獲取的是同一個對象。
在源碼註釋中提到一些特殊的類和接口:
Class
對象的類。具備相同元素類型和維數的數組,也具備相同的Class
對象(也就是說,元素類型不一樣,或數組維數不一樣,其Class
對象也不一樣)。boolean
, byte
, char
, short
, int
, long
, float
,double
)和關鍵字 void
也表示爲Class
對象。下面經過代碼來驗證:
@Test
public void testClassOther() {
// 枚舉是一種類
Class<PersonEnum> clazz1 = PersonEnum.class;
System.out.println("01 - " + clazz1);
// 註解是一種接口
Class<PersonAnnotation> clazz2 = PersonAnnotation.class;
System.out.println("02 - " + clazz2);
// 數組也屬於一個反應 Class 實例的類
Person[] personArray3 = new Person[1];
Class<? extends Person[]> clazz3 = personArray3.getClass();
System.out.println("03 - " + clazz3);
// 具備相同元素類型和維數的數組,也具備相同的 Class 實例
Person[] personArray4 = new Person[4];
Class<?> clazz4 = personArray4.getClass();
Person[][] personArray5 = new Person[1][];
Class<?> clazz5 = personArray5.getClass();
// 兩個一維數組的 hashCode 相等,說明是同一實例
System.out.println("04 - " + clazz3.hashCode());
System.out.println("05 - " + clazz4.hashCode());
// 一維數組與二維數組的 hashCode 不相等,說明不是同一實例
System.out.println("06 - " + clazz5.hashCode());
// 原始 Java 類型和關鍵字 void 也表示爲 Class 實例
Class<Integer> clazz6 = int.class;
System.out.println("07 - " + clazz6);
Class<Double> clazz7 = double.class;
System.out.println("08 - " + clazz7);
Class<Void> clazz8 = void.class;
System.out.println("09 - " + clazz8);
}
複製代碼
輸出結果:
01 - class io.github.gozhuyinglong.reflection.PersonEnum
02 - interface io.github.gozhuyinglong.reflection.PersonAnnotation
03 - class [Lio.github.gozhuyinglong.reflection.Person;
04 - 721748895
05 - 721748895
06 - 1642534850
07 - int
08 - double
09 - void
複製代碼
經過輸出結果能夠看出,確如源碼中描述那樣。
Java提供了一套反射API,該API由Class
類與java.lang.reflect
類庫組成。該類庫包含了Field
、Method
、Constructor
等類。這些類型的對象是由JVM在運行時建立的,用以表示未知類裏對應的成員。
反射容許以編程的方式訪問已加載類的字段、方法和構造函數信息,並在安全限制內利用反射對其進行操做。
下面將介紹一些經常使用的類:
java.lang.Class
類用來描述類的內部信息,Class
的實例能夠獲取類的包、註解、修飾符、名稱、超類、接口等。
@Test
public void testClass() throws Exception {
Class<?> clazz = Class.forName("io.github.gozhuyinglong.reflection.Person");
// 獲取該類所在包路徑
Package aPackage = clazz.getPackage();
System.out.println("01 - " + aPackage);
// 獲取該類上全部註解
Annotation[] declaredAnnotations = clazz.getDeclaredAnnotations();
for (Annotation temp : declaredAnnotations) {
System.out.println("02 - " + temp);
}
// 獲取類上的修飾符
int modifiers = clazz.getModifiers();
String modifier = Modifier.toString(modifiers);
System.out.println("03 - " + modifier);
// 獲取類名稱
String name = clazz.getName();
System.out.println("04 - " + name);
// 獲取簡單類名
String simpleName = clazz.getSimpleName();
System.out.println("05 - " + simpleName);
// 獲取直屬超類
Type genericSuperclass = clazz.getGenericSuperclass();
System.out.println("06 - " + genericSuperclass);
// 獲取直屬實現的接口
Type[] genericInterfaces = clazz.getGenericInterfaces();
for (Type temp : genericInterfaces) {
System.out.println("07 - " + temp);
}
}
複製代碼
輸出結果:
01 - package io.github.gozhuyinglong.reflection
02 - @io.github.gozhuyinglong.reflection.PersonAnnotation()
03 - public final
04 - io.github.gozhuyinglong.reflection.Person
05 - Person
06 - class io.github.gozhuyinglong.reflection.PersonParent
07 - interface io.github.gozhuyinglong.reflection.PersonInterface
複製代碼
java.lang.reflect.Constructor
提供了類的構造函數信息。能夠獲取構造函數上的註解信息、參數類型等。
@Test
public void testConstructor() throws Exception {
Class<?> clazz = Class.forName("io.github.gozhuyinglong.reflection.Person");
// 獲取一個聲明爲 public 構造函數實例
Constructor<?> constructor1 = clazz.getConstructor(String.class, int.class, PersonEnum.class);
System.out.println("01 - " + constructor1);
// 獲取全部聲明爲 public 構造函數實例
Constructor<?>[] constructorArray1 = clazz.getConstructors();
for (Constructor<?> constructor : constructorArray1) {
System.out.println("02 - " + constructor);
}
// 獲取一個聲明的構造函數實例
Constructor<?> constructor2 = clazz.getDeclaredConstructor(String.class);
System.out.println("03 - " + constructor2);
// 獲取全部聲明的構造函數實例
Constructor<?>[] constructorArray2 = clazz.getDeclaredConstructors();
for (Constructor<?> constructor : constructorArray2) {
System.out.println("04 - " + constructor);
}
// 根據構造函數建立一個實例
Object o1 = constructor1.newInstance("楊過", 25, PersonEnum.MAN);
System.out.println("05 - " + o1);
// 將構造函數的可訪問標誌設爲 true 後,能夠經過私有構造函數建立實例
constructor2.setAccessible(true);
Object o2 = constructor2.newInstance("小龍女");
System.out.println("06 - " + o2);
// 獲取該構造函數上的全部註解
Annotation[] annotations = constructor1.getDeclaredAnnotations();
for (Annotation annotation : annotations) {
System.out.println("07 - " + annotation);
}
// 獲取該構造函數上的全部參數類型
Type[] genericParameterTypes = constructor1.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println("08 - " + genericParameterType);
}
}
複製代碼
輸出結果:
01 - public io.github.gozhuyinglong.reflection.Person(java.lang.String,int,io.github.gozhuyinglong.reflection.PersonEnum)
02 - public io.github.gozhuyinglong.reflection.Person(java.lang.String,int,io.github.gozhuyinglong.reflection.PersonEnum)
02 - public io.github.gozhuyinglong.reflection.Person(java.lang.String,int)
02 - public io.github.gozhuyinglong.reflection.Person()
03 - private io.github.gozhuyinglong.reflection.Person(java.lang.String)
04 - public io.github.gozhuyinglong.reflection.Person(java.lang.String,int,io.github.gozhuyinglong.reflection.PersonEnum)
04 - public io.github.gozhuyinglong.reflection.Person(java.lang.String,int)
04 - private io.github.gozhuyinglong.reflection.Person(java.lang.String)
04 - public io.github.gozhuyinglong.reflection.Person()
05 - Person{name='楊過', age=25, sex='MAN'}
06 - Person{name='小龍女', age=0, sex='null'}
07 - @io.github.gozhuyinglong.reflection.PersonAnnotation()
08 - class java.lang.String
08 - int
08 - class io.github.gozhuyinglong.reflection.PersonEnum
複製代碼
java.lang.reflect.Field
提供了類的屬性信息。能夠獲取屬性上的註解、修飾符、屬性類型、屬性名等。
@Test
public void testField() throws Exception {
Class<?> clazz = Class.forName("io.github.gozhuyinglong.reflection.Person");
// 獲取一個該類或父類中聲明爲 public 的屬性
Field field1 = clazz.getField("hobby");
System.out.println("01 - " + field1);
// 獲取該類及父類中全部聲明爲 public 的屬性
Field[] fieldArray1 = clazz.getFields();
for (Field field : fieldArray1) {
System.out.println("02 - " + field);
}
// 獲取一個該類中聲明的屬性
Field field2 = clazz.getDeclaredField("name");
System.out.println("03 - " + field2);
// 獲取該類中全部聲明的屬性
Field[] fieldArray2 = clazz.getDeclaredFields();
for (Field field : fieldArray2) {
System.out.println("04 - " + field);
}
// 獲取該屬性上的全部註解
Annotation[] declaredAnnotations = field2.getDeclaredAnnotations();
for (Annotation declaredAnnotation : declaredAnnotations) {
System.out.println("05 - " + declaredAnnotation);
}
// 獲取修飾符
String modifier = Modifier.toString(field2.getModifiers());
System.out.println("06 - " + modifier);
// 獲取屬性類型,返回類對象
Class<?> type = field2.getType();
System.out.println("07 - " + type);
// 獲取屬性類型,返回Type對象
Type genericType = field2.getGenericType();
System.out.println("08 - " + genericType);
// 獲取屬性名稱
String name = field2.getName();
System.out.println("09 - " + name);
}
複製代碼
輸出結果:
01 - public java.lang.String io.github.gozhuyinglong.reflection.PersonParent.hobby
02 - public int io.github.gozhuyinglong.reflection.Person.height
02 - public java.lang.String io.github.gozhuyinglong.reflection.PersonParent.hobby
03 - private java.lang.String io.github.gozhuyinglong.reflection.Person.name
04 - private java.lang.String io.github.gozhuyinglong.reflection.Person.name
04 - private int io.github.gozhuyinglong.reflection.Person.age
04 - public int io.github.gozhuyinglong.reflection.Person.height
05 - @io.github.gozhuyinglong.reflection.PersonAnnotation()
06 - private
07 - class java.lang.String
08 - class java.lang.String
09 - name
複製代碼
java.lang.reflect.Method
提供了類的方法信息。能夠獲取方法上的註解、修飾符、返回值類型、方法名稱、全部參數。
@Test
public void testMethod() throws Exception {
Class<?> clazz = Class.forName("io.github.gozhuyinglong.reflection.Person");
// 獲取一個該類及父類中聲明爲 public 的方法,須要指定方法的入參類型
Method method = clazz.getMethod("setName", String.class);
System.out.println("01 - " + method);
// 獲取該類及父類中全部聲明爲 public 的方法
Method[] methods = clazz.getMethods();
for (Method temp : methods) {
System.out.println("02 - " + temp);
}
// 獲取一個在該類中聲明的方法
Method declaredMethod = clazz.getDeclaredMethod("display");
System.out.println("03 - " + declaredMethod);
// 獲取全部在該類中聲明的方法
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method temp : declaredMethods) {
System.out.println("04 - " + temp);
}
// 獲取該方法上的全部註解
Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
for (Annotation temp : declaredAnnotations) {
System.out.println("05 - " + temp);
}
// 獲取修飾符
String modifier = Modifier.toString(method.getModifiers());
System.out.println("06 - " + modifier);
// 獲取返回值類型,返回類對象
Class<?> returnType = method.getReturnType();
System.out.println("07 - " + returnType);
// 獲取返回值類型,返回Type對象
Type genericReturnType = method.getGenericReturnType();
System.out.println("08 - " + genericReturnType);
// 獲取方法名稱
String name = method.getName();
System.out.println("09 - " + name);
// 獲取全部入參
Parameter[] parameters = method.getParameters();
for (Parameter temp : parameters) {
System.out.println("10 - " + temp);
}
}
複製代碼
輸出結果:
01 - public void io.github.gozhuyinglong.reflection.Person.setName(java.lang.String)
02 - public java.lang.String io.github.gozhuyinglong.reflection.Person.toString()
02 - public java.lang.String io.github.gozhuyinglong.reflection.Person.getName()
02 - public void io.github.gozhuyinglong.reflection.Person.setName(java.lang.String)
02 - public int io.github.gozhuyinglong.reflection.Person.getAge()
02 - public void io.github.gozhuyinglong.reflection.Person.setAge(int)
02 - public java.lang.String io.github.gozhuyinglong.reflection.Person.sayHello()
02 - public io.github.gozhuyinglong.reflection.PersonEnum io.github.gozhuyinglong.reflection.PersonParent.getSex()
02 - public void io.github.gozhuyinglong.reflection.PersonParent.setSex(io.github.gozhuyinglong.reflection.PersonEnum)
02 - public final void java.lang.Object.wait() throws java.lang.InterruptedException
02 - public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
02 - public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
02 - public boolean java.lang.Object.equals(java.lang.Object)
02 - public native int java.lang.Object.hashCode()
02 - public final native java.lang.Class java.lang.Object.getClass()
02 - public final native void java.lang.Object.notify()
02 - public final native void java.lang.Object.notifyAll()
03 - private java.lang.String io.github.gozhuyinglong.reflection.Person.display()
04 - public java.lang.String io.github.gozhuyinglong.reflection.Person.toString()
04 - public java.lang.String io.github.gozhuyinglong.reflection.Person.getName()
04 - public void io.github.gozhuyinglong.reflection.Person.setName(java.lang.String)
04 - private java.lang.String io.github.gozhuyinglong.reflection.Person.display()
04 - public int io.github.gozhuyinglong.reflection.Person.getAge()
04 - public void io.github.gozhuyinglong.reflection.Person.setAge(int)
04 - public java.lang.String io.github.gozhuyinglong.reflection.Person.sayHello()
05 - @io.github.gozhuyinglong.reflection.PersonAnnotation()
06 - public
07 - void
08 - void
09 - setName
10 - java.lang.String arg0
複製代碼
java.lang.reflect.Modifier
提供了訪問修飾符信息。經過Class
、Field
、Method
、Constructor
等對象均可以獲取修飾符,這個訪問修飾符是一個整數,能夠經過Modifier.toString
方法來查看修飾符描述。而且該類提供了一些靜態方法和常量來解碼訪問修飾符。
@Test
public void testModifier() throws Exception {
Class<?> clazz = Class.forName("io.github.gozhuyinglong.reflection.Person");
// 獲取類的修飾符值
int modifiers1 = clazz.getModifiers();
System.out.println("01 - " + modifiers1);
// 獲取屬性的修飾符值
int modifiers2 = clazz.getDeclaredField("name").getModifiers();
System.out.println("02 - " + modifiers2);
// 獲取構造函數的修飾符值
int modifiers3 = clazz.getDeclaredConstructor(String.class).getModifiers();
System.out.println("03 - " + modifiers3);
// 獲取方法的修飾符值
int modifiers4 = clazz.getDeclaredMethod("display").getModifiers();
System.out.println("04 - " + modifiers4);
// 判斷修飾符值是否 final 類型
boolean isFinal = Modifier.isFinal(modifiers1);
System.out.println("05 - " + isFinal);
// 判斷修飾符值是否 public 類型
boolean isPublic = Modifier.isPublic(modifiers2);
System.out.println("06 - " + isPublic);
// 根據修飾符值,獲取修飾符標誌的字符串
String modifier = Modifier.toString(modifiers1);
System.out.println("07 - " + modifier);
System.out.println("08 - " + Modifier.toString(modifiers2));
}
複製代碼
輸出結果:
01 - 17
02 - 2
03 - 2
04 - 2
05 - true
06 - false
07 - public final
08 - private
複製代碼
java.lang.reflect.Parameter
提供了方法的參數信息。能夠獲取方法上的註解、參數名稱、參數類型等。
@Test
public void testParameter() throws Exception {
Class<?> clazz = Class.forName("io.github.gozhuyinglong.reflection.Person");
// 獲取構造函數的參數
Constructor<?> constructor = clazz.getConstructor(String.class, int.class, PersonEnum.class);
Parameter[] parameterArray1 = constructor.getParameters();
for (Parameter temp : parameterArray1) {
System.out.println("01 - " + temp);
}
// 獲取方法的參數
Method method = clazz.getMethod("setName", String.class);
Parameter[] parameterArray2 = method.getParameters();
for (Parameter temp : parameterArray2) {
System.out.println("02 - " + temp);
}
Parameter parameter = parameterArray1[0];
// 獲取參數上的註解
Annotation[] annotationArray = parameter.getAnnotations();
for (Annotation temp : annotationArray) {
System.out.println("02 - " + temp);
}
// 獲取參數名稱
String name = parameter.getName();
System.out.println("03 - " + name);
// 獲取參數類型
Type parameterizedType = parameter.getParameterizedType();
System.out.println("04 - " + parameterizedType);
Class<?> type = parameter.getType();
System.out.println("05 - " + type);
}
複製代碼
輸出結果:
01 - java.lang.String arg0
01 - int arg1
01 - io.github.gozhuyinglong.reflection.PersonEnum arg2
02 - java.lang.String arg0
02 - @io.github.gozhuyinglong.reflection.PersonAnnotation()
03 - arg0
04 - class java.lang.String
05 - class java.lang.String
複製代碼
java.lang.reflect.AccessibleObject
類是Field
、Method
和Constructor
類的超類。
該類提供了對類、方法、構造函數的訪問控制檢查的能力(如:私有方法只容許當前類訪問)。
該訪問檢查在設置/獲取屬性、調用方法、建立/初始化類的實例時執行。
能夠經過setAccessible
方法將可訪問標誌設爲true
(默認爲false
),會關閉訪問檢查。這樣即便是私有的屬性、方法或構造函數,也能夠訪問。
能夠利用反射來建立對象,並可執行方法,下面看代碼示例:
Class
類的newInstance
建立一個實例。(該方法調用無參構造器)。Constructor
類建立一個實例。invoke
方法來調用,第一個參數爲實例,後面參數爲方法的Parameter
。set
方法來賦值。@Test
public void testInvoke() throws Exception {
Class<?> clazz = Class.forName("io.github.gozhuyinglong.reflection.Person");
// 經過Class類的newInstance建立一個實例。(該方法調用無參構造器)
Object o1 = clazz.newInstance();
System.out.println("01 - " + o1.toString());
// 經過構造函數Constructor類建立一個實例
Constructor<?> constructor = clazz.getConstructor(String.class, int.class, PersonEnum.class);
Object o2 = constructor.newInstance("楊過", 25, PersonEnum.MAN);
System.out.println("02 - " + o2.toString());
// 先獲取方法,再經過 invoke 方法來調用,第一個參數爲實例,後面參數爲方法的Parameter
Method method = clazz.getMethod("setName", String.class);
method.invoke(o1, "小龍女");
System.out.println("03 - " + o1.toString());
// 獲取字段,由於 age 字段是私有的,因此將其設置爲可訪問(不設置會報異常)。並經過 set 方法來賦值
Field field = clazz.getDeclaredField("age");
field.setAccessible(true);
field.set(o1, 28);
System.out.println("04 - " + o1.toString());
}
複製代碼
執行結果:
01 - Person{name='null', age=0, sex='null'}
02 - Person{name='楊過', age=25, sex='MAN'}
03 - Person{name='小龍女', age=0, sex='null'}
04 - Person{name='小龍女', age=28, sex='null'}
複製代碼
引自官方指南:docs.oracle.com/javase/tuto…
反射雖是強大的,但不可隨意使用。若是能夠在不使用反射的狀況下執行操做,則應避免使用它。由於經過反射訪問代碼時,會有如下缺點。
反射包括了一些動態類型,因此JVM沒法對這些代碼進行優化。所以,反射操做的效率要比那些非反射操做低得多。咱們應該避免在常常被執行的代碼或對性能要求很高的程序中使用反射。
使用反射技術要求程序必須在一個沒有安全限制的環境中運行。若是一個程序必須在有安全限制的環境中運行,如Applet,那麼這就是個問題了。
因爲反射容許代碼執行一些在正常狀況下不被容許的操做,好比訪問私有的屬性和方法。因此使用反射可能會致使意料以外的反作用:代碼有功能上的錯誤,下降可移植性。反射代碼破壞了抽象性,所以當平臺發生改變的時候,代碼的行爲就有可能也隨着變化。
完整代碼請訪問個人Github,若對你有幫助,歡迎給個⭐,感謝~~🌹🌹🌹