Java核心技術(shù)之反射
一、Class類與Java反射
Class textFieldC=tetxField.getClass(); //tetxField為JTextField類對象
反射可訪問的主要描述
1、訪問構(gòu)造方法
每個Constructor對象代表一個構(gòu)造方法,利用Constructor對象可以操縱相應的構(gòu)造方法。
getConstructors()
//獲取公有getConstructor(Class<?>... parameterTypes)
//獲取指定公有getDeclaredConstructors()
//獲取所有getDeclaredConstructor(Class<?>... parameterTypes)
//獲取指定方法
創(chuàng)建Demo1類,聲明String類型成員變量和3個int類型成員變量,并提供3個構(gòu)造方法。
package bao; public class Demo1{ String s; int i,i2,i3; private Demo1() { } protected Demo1(String s,int i) { this.s=s; this.i=i; } public Demo1(String... strings)throws NumberFormatException{ if(0<strings.length) { i=Integer.valueOf(strings[0]); } if(1<strings.length) { i2=Integer.valueOf(strings[0]); } if(2<strings.length) { i3=Integer.valueOf(strings[0]); } } public void print() { System.out.println("s="+s); System.out.println("i="+i); System.out.println("i2="+i2); System.out.println("i3="+i3); } }
編寫Main類,在該類對Demo1進行反射訪問的所有構(gòu)造方法,并將該構(gòu)造方法是否允許帶有可變數(shù)量的參數(shù)、入口參數(shù)和可能拋出的異常類型信息輸出。
package bao; import java.lang.reflect.Constructor; public class Main { public static void main(String[] args) { Demo1 demo=new Demo1("10","20","30"); Class<? extends Demo1>demoC=demo.getClass(); //獲得所有構(gòu)造方法 Constructor[] declaredConstryctors=demoC.getDeclaredConstructors(); for(int i=0;i<declaredConstryctors.length;i++) { Constructor<?> constructor=declaredConstryctors[i]; System.out.println("查看是否允許帶有可變數(shù)量的參數(shù):"+constructor.isVarArgs()); System.out.println("該構(gòu)造方法的入口參數(shù)類型依次為:"); Class[]parameterTypes=constructor.getParameterTypes(); //獲取所有參數(shù)類型 for(int j=0;j<parameterTypes.length;j++) { System.out.println(" "+parameterTypes[j]); } System.out.println("該構(gòu)造方法的入口可能拋出異常類型為:"); //獲取所有可能拋出的異常信息類型 Class[] exceptionTypes=constructor.getExceptionTypes(); for(int j=0;j<exceptionTypes.length;j++) { System.out.println(" "+exceptionTypes[j]); } Demo1 example2=null; while(example2==null) { try { if(i==2) { example2=(Demo1)constructor.newInstance(); }else if(i==1) { example2=(Demo1)constructor.newInstance("7",5); }else { Object[] parameters=new Object[] {new String[] {"100","200","300"}}; example2=(Demo1)constructor.newInstance(parameters); } }catch(Exception e){ System.out.println("在創(chuàng)建對象時拋出異常,下面執(zhí)行setAccessible()方法"); constructor.setAccessible(true); //設置允許訪問 } } if(example2!=null) { example2.print(); System.out.println(); } } } } /*輸出結(jié)果: 查看是否允許帶有可變數(shù)量的參數(shù):true 該構(gòu)造方法的入口參數(shù)類型依次為: class [Ljava.lang.String; 該構(gòu)造方法的入口可能拋出異常類型為: class java.lang.NumberFormatException s=null i=100 i2=100 i3=100 查看是否允許帶有可變數(shù)量的參數(shù):false 該構(gòu)造方法的入口參數(shù)類型依次為: class java.lang.String int 該構(gòu)造方法的入口可能拋出異常類型為: s=7 i=5 i2=0 i3=0 查看是否允許帶有可變數(shù)量的參數(shù):false 該構(gòu)造方法的入口參數(shù)類型依次為: 該構(gòu)造方法的入口可能拋出異常類型為: 在創(chuàng)建對象時拋出異常,下面執(zhí)行setAccessible()方法 s=null i=0 i2=0 i3=0 */
2、訪問成員變量
每個Field對象代表一個成員變量,利用Field對象可以操縱相應的成員變量。
- getFields()
- getField(String name)
- getDeclaredFields()
- getDeclaredField(String name)
創(chuàng)建Demo1類依次聲明int、fioat、boolean和String類型的成員變量,并設置不同的訪問權(quán)。
package bao; public class Demo1{ int i; public float f; protected boolean b; private String s; }
通過反射訪問Demo1類中的所有成員變量,將成成員變量的名稱和類型信息輸出。
package bao; import java.lang.reflect.Field; public class Main { public static void main(String[] args) { Demo1 demo=new Demo1(); Class demoC=demo.getClass(); //獲得所有成員變量 Field[] declaredField=demoC.getDeclaredFields(); for(int i=0;i<declaredField.length;i++) { Field field=declaredField[i]; System.out.println("名稱為:"+field.getName()); //獲取成員變量名稱 Class fieldType=field.getType(); ///獲取成員變量類型 System.out.println("類型為:"+fieldType); boolean isTurn=true; while(isTurn) { try { isTurn=false; System.out.println("修改前的值為:"+field.get(demo)); if(fieldType.equals(int.class)) { //判斷成員變量的類型是否為int類型 System.out.println("利用方法setInt()修改成員變量的值"); field.setInt(demo, 168); //為int類型成員變量賦值 }else if(fieldType.equals(float.class)){ //判斷成員變量的類型是否為float類型 System.out.println("利用方法 setFloat()修改成員變量的值"); field.setFloat(demo, 99.9F); //為float類型成員變量賦值 }else if(fieldType.equals(boolean.class)){ //判斷成員變量的類型是否為boolean類型 System.out.println("利用方法 setBoolean()修改成員變量的值"); field.setBoolean(demo, true); //為boolean類型成員變量賦值 }else { System.out.println("利用方法 set()修改成員變量的值"); field.set(demo, "MWQ"); //可以為各種類型的成員變量賦值 } //獲得成員變量值 System.out.println("修改后的值為:"+field.get(demo)); }catch(Exception e) { System.out.println("在設置成員變量值時拋出異常,"+"下面執(zhí)行setAccesssible()方法!"); field.setAccessible(true); //設置為允許訪問 isTurn=true; } } System.out.println(); } } }
/*輸出結(jié)果:
名稱為:i
類型為:int
修改前的值為:0
利用方法setInt()修改成員變量的值
修改后的值為:168
名稱為:f
類型為:float
修改前的值為:0.0
利用方法 setFloat()修改成員變量的值
修改后的值為:99.9
名稱為:b
類型為:boolean
修改前的值為:false
利用方法 setBoolean()修改成員變量的值
修改后的值為:true
名稱為:s
類型為:class java.lang.String
在設置成員變量值時拋出異常,下面執(zhí)行setAccesssible()方法!
修改前的值為:null
利用方法 set()修改成員變量的值
修改后的值為:MWQ
*/
3、訪問方法
每個Method對象代表一個方法,利用Method對象可以操縱相應的方法。
- getMethods()
- getMethod(String name, Class<?>... parameterTypes)
- getDeclaredMethods()
- getDeclaredMethod(String name, Class<?>... parameterTypes)
創(chuàng)建Demo1類,編寫4個典型方法。
package bao; public class Demo1{ static void staitcMethod() { System.out.println("執(zhí)行staitcMethod()方法"); } public int publicMethod(int i) { System.out.println("執(zhí)行publicMethod()方法"); return i*100; } protected int protectedMethod(String s,int i)throws NumberFormatException { System.out.println("執(zhí)行protectedMethod()方法"); return Integer.valueOf(s)+i; } private String privateMethod(String...strings) { System.out.println("執(zhí)行privateMethod()方法"); StringBuffer stringBuffer=new StringBuffer(); for(int i=0;i<stringBuffer.length();i++) { stringBuffer.append(strings[i]); } return stringBuffer.toString(); } }
反射訪問Demm1類中的所有方法,將方法的名稱、入口參數(shù)類型、返回值類型等信息輸出
package bao; import java.lang.reflect.Field; import java.lang.reflect.Method; public class Main { public static void main(String[] args) { Demo1 demo = new Demo1(); Class demoC = demo.getClass(); // 獲得所有方法 Method[] declaredMethods = demoC.getDeclaredMethods(); for (int i = 0; i < declaredMethods.length; i++) { Method method = declaredMethods[i]; // 遍歷方法 System.out.println("名稱為:" + method.getName()); // 獲得方法名稱 System.out.println("是否允許帶有可變數(shù)量的參數(shù):" + method.isVarArgs()); System.out.println("入口參數(shù)類型依次為:"); // 獲得所有參數(shù)類型 Class[] parameterTypes = method.getParameterTypes(); for (int j = 0; j < parameterTypes.length; j++) { System.out.println(" " + parameterTypes[j]); } // 獲得方法返回值類型 System.out.println("返回值類型為:" + method.getReturnType()); System.out.println("可能拋出的異常類型有:"); // 獲得方法可能拋出的所有異常類型 Class[] exceptionTypes = method.getExceptionTypes(); for (int j = 0; j < exceptionTypes.length; j++) { System.out.println(" " + exceptionTypes[j]); } boolean isTurn = true; while (isTurn) { try { isTurn = false; if("staitcMethod".equals(method.getName())) { method.invoke(demo); // 執(zhí)行沒有入口參數(shù)的方法 }else if("publicMethod".equals(method.getName())) { System.out.println("返回值為:"+ method.invoke(demo, 168)); // 執(zhí)行方法 }else if("protectedMethod".equals(method.getName())) { System.out.println("返回值為:"+ method.invoke(demo, "7", 5)); // 執(zhí)行方法 }else { Object[] parameters = new Object[] { new String[] {"M", "W", "Q" } }; // 定義二維數(shù)組 System.out.println("返回值為:"+ method.invoke(demo, parameters)); } }catch(Exception e) { System.out.println("在執(zhí)行方法時拋出異常," + "下面執(zhí)行setAccessible()方法!"); method.setAccessible(true); // 設置為允許訪問 isTurn = true; } } System.out.println(); } } }
/*輸出結(jié)果:
名稱為:publicMethod
是否允許帶有可變數(shù)量的參數(shù):false
入口參數(shù)類型依次為:
int
返回值類型為:int
可能拋出的異常類型有:
執(zhí)行publicMethod()方法
返回值為:16800
名稱為:staitcMethod
是否允許帶有可變數(shù)量的參數(shù):false
入口參數(shù)類型依次為:
返回值類型為:void
可能拋出的異常類型有:
執(zhí)行staitcMethod()方法
名稱為:protectedMethod
是否允許帶有可變數(shù)量的參數(shù):false
入口參數(shù)類型依次為:
class java.lang.String
int
返回值類型為:int
可能拋出的異常類型有:
class java.lang.NumberFormatException
執(zhí)行protectedMethod()方法
返回值為:12
名稱為:privateMethod
是否允許帶有可變數(shù)量的參數(shù):true
入口參數(shù)類型依次為:
class [Ljava.lang.String;
返回值類型為:class java.lang.String
可能拋出的異常類型有:
在執(zhí)行方法時拋出異常,下面執(zhí)行setAccessible()方法!
執(zhí)行privateMethod()方法
返回值為:
*/
二、使用Annotation功能
1、定義Annotation類型
在定義Annotation類型時,也需要用到用來定義接口的interface關(guān)鍵字,不過需要在interface關(guān)鍵字前加一個“@”符號,即定義Annotation類型的關(guān)鍵字為@interface,這個關(guān)鍵字的隱含意思是繼承了java.lang.annotation.Annotation接口。
public @interface NoMemberAnnotation{
String value();
}
@interface
:聲明關(guān)鍵字。
NoMemberAnnotation
:注解名稱。
String
:成員類型。
value
:成員名稱。
定義并使用Annotation類型
①定義Annotation類型@Constructor_Annotation的有效范圍為運行時加載Annotation到JVM中。
package annotationbao; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.CONSTRUCTOR) // 用于構(gòu)造方法 @Retention(RetentionPolicy.RUNTIME) // 在運行時加載Annotation到JVM中 public @interface Constructor_Annotation{ String value() default "默認構(gòu)造方法"; // 定義一個具有默認值的String型成員 }
②定義一個來注釋字段、方法和參數(shù)的Annotation類型@Field_Method_Parameter_Annotation的有效范圍為運行時加載Annotation到JVM中
package annotationbao; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER}) // 用于字段、方法和參數(shù) @Retention(RetentionPolicy.RUNTIME) // 在運行時加載Annotation到JVM中 public @interface Field_Method_Parameter_Annotation{ String descrblic(); // 定義一個沒有默認值的String型成員 Class type() default void.class; // 定義一個具有默認值的Class型成員 }
③編寫一個Record類,在該類中運用前面定義Annotation類型的@Constructor_Annotation和@Field_Method_Parameter_Annotation對構(gòu)造方法、字段、方法和參數(shù)進行注釋。
package annotationbao; public class Record { @Field_Method_Parameter_Annotation(describe = "編號", type = int.class) int id; @Field_Method_Parameter_Annotation(describe = "姓名", type = String.class) String name; @Constructor_Annotation() public Record() { } @Constructor_Annotation("立即初始化構(gòu)造方法") public Record( @Field_Method_Parameter_Annotation(describe = "編號", type = int.class) int id, @Field_Method_Parameter_Annotation(describe = "姓名", type = String.class) String name) { this.id = id; this.name = name; } @Field_Method_Parameter_Annotation(describe = "獲得編號", type = int.class) public int getId() { return id; } @Field_Method_Parameter_Annotation(describe = "設置編號") public void setId( @Field_Method_Parameter_Annotation(describe = "編號", type = int.class)int id) { this.id = id; } @Field_Method_Parameter_Annotation(describe = "獲得姓名", type = String.class) public String getName() { return name; } @Field_Method_Parameter_Annotation(describe = "設置姓名") public void setName( @Field_Method_Parameter_Annotation(describe = "姓名", type = String.class)String name) { this.name = name; } }
2、訪問Annotation信息
如果在定義Annotation類型時將@Retention設置為RetentionPolicy.RUNTIME,那么在運行程序時通過反射就可以獲取到相關(guān)的Annotation信息,如獲取構(gòu)造方法、字段和方法的Annotation信息。
聯(lián)合以上的定義并使用Annotation類型,通過反射訪問Record類中的Annotation信息。
package annotationbao; import java.lang.annotation.*; import java.lang.reflect.*; public class Main_05 { public static void main(String[] args) { Class recordC = null; try { recordC = Class.forName("Record"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("------ 構(gòu)造方法的描述如下 ------"); Constructor[] declaredConstructors = recordC .getDeclaredConstructors(); // 獲得所有構(gòu)造方法 for (int i = 0; i < declaredConstructors.length; i++) { Constructor constructor = declaredConstructors[i]; // 遍歷構(gòu)造方法 // 查看是否具有指定類型的注釋 if (constructor .isAnnotationPresent(Constructor_Annotation.class)) { // 獲得指定類型的注釋 Constructor_Annotation ca = (Constructor_Annotation) constructor .getAnnotation(Constructor_Annotation.class); System.out.println(ca.value()); // 獲得注釋信息 } Annotation[][] parameterAnnotations = constructor .getParameterAnnotations(); // 獲得參數(shù)的注釋 for (int j = 0; j < parameterAnnotations.length; j++) { // 獲得指定參數(shù)注釋的長度 int length = parameterAnnotations[j].length; if (length == 0) // 如果長度為0則表示沒有為該參數(shù)添加注釋 System.out.println(" 未添加Annotation的參數(shù)"); else for (int k = 0; k < length; k++) { // 獲得參數(shù)的注釋 Field_Method_Parameter_Annotation pa = (Field_Method_Parameter_Annotation) parameterAnnotations[j][k]; System.out.print(" " + pa.describe()); // 獲得參數(shù)描述 System.out.println(" " + pa.type()); // 獲得參數(shù)類型 } } System.out.println(); } System.out.println(); System.out.println("-------- 字段的描述如下 --------"); Field[] declaredFields = recordC.getDeclaredFields(); // 獲得所有字段 for (int i = 0; i < declaredFields.length; i++) { Field field = declaredFields[i]; // 遍歷字段 // 查看是否具有指定類型的注釋 if (field .isAnnotationPresent(Field_Method_Parameter_Annotation.class)) { // 獲得指定類型的注釋 Field_Method_Parameter_Annotation fa = field .getAnnotation(Field_Method_Parameter_Annotation.class); System.out.print(" " + fa.describe()); // 獲得字段的描述 System.out.println(" " + fa.type()); // 獲得字段的類型 } } System.out.println(); System.out.println("-------- 方法的描述如下 --------"); Method[] methods = recordC.getDeclaredMethods(); // 獲得所有方法 for (int i = 0; i < methods.length; i++) { Method method = methods[i]; // 遍歷方法 // 查看是否具有指定類型的注釋 if (method .isAnnotationPresent(Field_Method_Parameter_Annotation.class)) { // 獲得指定類型的注釋 Field_Method_Parameter_Annotation ma = method .getAnnotation(Field_Method_Parameter_Annotation.class); System.out.println(ma.describe()); // 獲得方法的描述 System.out.println(ma.type()); // 獲得方法的返回值類型 } Annotation[][] parameterAnnotations = method .getParameterAnnotations(); // 獲得參數(shù)的注釋 for (int j = 0; j < parameterAnnotations.length; j++) { int length = parameterAnnotations[j].length; // 獲得指定參數(shù)注釋的長度 if (length == 0) // 如果長度為0表示沒有為該參數(shù)添加注釋 System.out.println(" 未添加Annotation的參數(shù)"); else for (int k = 0; k < length; k++) { // 獲得指定類型的注釋 Field_Method_Parameter_Annotation pa = (Field_Method_Parameter_Annotation) parameterAnnotations[j][k]; System.out.print(" " + pa.describe()); // 獲得參數(shù)的描述 System.out.println(" " + pa.type()); // 獲得參數(shù)的類型 } } System.out.println(); } } }
/*輸出結(jié)果:
------ 構(gòu)造方法的描述如下 ------
默認構(gòu)造方法
立即初始化構(gòu)造方法
編號 int
姓名 class java.lang.String
-------- 字段的描述如下 --------
編號 int
姓名 class java.lang.String
-------- 方法的描述如下 --------
獲得姓名
class java.lang.String
設置姓名
void
姓名 class java.lang.String
獲得編號
int
設置編號
void
編號 int
*/
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
基于Mybatis-Plus攔截器實現(xiàn)MySQL數(shù)據(jù)加解密的示例代碼
用戶的一些敏感數(shù)據(jù),例如手機號、郵箱、身份證等信息,在數(shù)據(jù)庫以明文存儲時會存在數(shù)據(jù)泄露的風險,因此需要進行加密,解密等功能,接下來本文就給大家介紹基于Mybatis-Plus攔截器實現(xiàn)MySQL數(shù)據(jù)加解密,需要的朋友可以參考下2023-07-07Spring Cloud OAuth2中/oauth/token的返回內(nèi)容格式
Spring Cloud OAuth2 生成access token的請求/oauth/token的返回內(nèi)容就需要自定義,本文就詳細介紹一下,感興趣的可以了解一下2021-07-07FeignClientFactoryBean創(chuàng)建動態(tài)代理詳細解讀
這篇文章主要介紹了FeignClientFactoryBean創(chuàng)建動態(tài)代理詳細解讀,當直接進去注冊的方法中,一步步放下走,都是直接放bean的定義信息中放入值,然后轉(zhuǎn)成BeanDefinitionHolder,最后在注冊到IOC容器中,需要的朋友可以參考下2023-11-11SpringData JPA快速上手之關(guān)聯(lián)查詢及JPQL語句書寫詳解
JPA都有SpringBoot的官方直接提供的starter,而Mybatis沒有,直到SpringBoot 3才開始加入到官方模版中,這篇文章主要介紹了SpringData JPA快速上手,關(guān)聯(lián)查詢,JPQL語句書寫的相關(guān)知識,感興趣的朋友一起看看吧2023-09-09java中建立0-10m的消息(字符串)實現(xiàn)方法
下面小編就為大家?guī)硪黄猨ava中建立0-10m的消息(字符串)實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05基于@PostConstruct注解的使用,解決向靜態(tài)變量注入值
這篇文章主要介紹了基于@PostConstruct注解的使用,解決向靜態(tài)變量注入值問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09