一、Class類與Java反射
Class textFieldC=tetxField.getClass(); //tetxField為JTextField類物件
反射可訪問的主要描述

1、訪問構造方法
每個Constructor物件代表一個構造方法,利用Constructor物件可以操縱相應的構造方法,
- getConstructors() //獲取公有
- getConstructor(Class<?>... parameterTypes) //獲取指定公有
- getDeclaredConstructors() //獲取所有
- getDeclaredConstructor(Class<?>... parameterTypes) //獲取指定方法
創建Demo1類,宣告String型別成員變數和3個int型別成員變數,并提供3個構造方法,
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進行反射訪問的所有構造方法,并將該構造方法是否允許帶有可變數量的引數、入口引數和可能拋出的例外型別資訊輸出,
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();
//獲得所有構造方法
Constructor[] declaredConstryctors=demoC.getDeclaredConstructors();
for(int i=0;i<declaredConstryctors.length;i++) {
Constructor<?> constructor=declaredConstryctors[i];
System.out.println("查看是否允許帶有可變數量的引數:"+constructor.isVarArgs());
System.out.println("該構造方法的入口引數型別依次為:");
Class[]parameterTypes=constructor.getParameterTypes(); //獲取所有引數型別
for(int j=0;j<parameterTypes.length;j++) {
System.out.println(" "+parameterTypes[j]);
}
System.out.println("該構造方法的入口可能拋出例外型別為:");
//獲取所有可能拋出的例外資訊型別
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("在創建物件時拋出例外,下面執行setAccessible()方法");
constructor.setAccessible(true); //設定允許訪問
}
}
if(example2!=null) {
example2.print();
System.out.println();
}
}
}
}
/*輸出結果:
查看是否允許帶有可變數量的引數:true
該構造方法的入口引數型別依次為:
class [Ljava.lang.String;
該構造方法的入口可能拋出例外型別為:
class java.lang.NumberFormatException
s=null
i=100
i2=100
i3=100
查看是否允許帶有可變數量的引數:false
該構造方法的入口引數型別依次為:
class java.lang.String
int
該構造方法的入口可能拋出例外型別為:
s=7
i=5
i2=0
i3=0
查看是否允許帶有可變數量的引數:false
該構造方法的入口引數型別依次為:
該構造方法的入口可能拋出例外型別為:
在創建物件時拋出例外,下面執行setAccessible()方法
s=null
i=0
i2=0
i3=0
*/
2、訪問成員變數
每個Field物件代表一個成員變數,利用Field物件可以操縱相應的成員變數,
- getFields()
- getField(String name)
- getDeclaredFields()
- getDeclaredField(String name)
創建Demo1類依次宣告int、fioat、boolean和String型別的成員變數,并設定不同的訪問權,
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("在設定成員變數值時拋出例外,"+"下面執行setAccesssible()方法!");
field.setAccessible(true); //設定為允許訪問
isTurn=true;
}
}
System.out.println();
}
}
}
/*輸出結果:
名稱為:i
型別為:int
修改前的值為:0
利用方法setInt()修改成員變數的值
修改后的值為:168
名稱為:f
型別為:float
修改前的值為:0.0
利用方法 setFloat()修改成員變數的值
修改后的值為:99.9
名稱為:b
型別為:boolean
修改前的值為:false
利用方法 setBoolean()修改成員變數的值
修改后的值為:true
名稱為:s
型別為:class java.lang.String
在設定成員變數值時拋出例外,下面執行setAccesssible()方法!
修改前的值為:null
利用方法 set()修改成員變數的值
修改后的值為:MWQ
*/
3、訪問方法
每個Method物件代表一個方法,利用Method物件可以操縱相應的方法,
- getMethods()
- getMethod(String name, Class<?>... parameterTypes)
- getDeclaredMethods()
- getDeclaredMethod(String name, Class<?>... parameterTypes)
創建Demo1類,撰寫4個典型方法,
package bao;
public class Demo1{
static void staitcMethod() {
System.out.println("執行staitcMethod()方法");
}
public int publicMethod(int i) {
System.out.println("執行publicMethod()方法");
return i*100;
}
protected int protectedMethod(String s,int i)throws NumberFormatException {
System.out.println("執行protectedMethod()方法");
return Integer.valueOf(s)+i;
}
private String privateMethod(String...strings) {
System.out.println("執行privateMethod()方法");
StringBuffer stringBuffer=new StringBuffer();
for(int i=0;i<stringBuffer.length();i++) {
stringBuffer.append(strings[i]);
}
return stringBuffer.toString();
}
}
反射訪問Demm1類中的所有方法,將方法的名稱、入口引數型別、回傳值型別等資訊輸出
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("是否允許帶有可變數量的引數:" + method.isVarArgs());
System.out.println("入口引數型別依次為:");
// 獲得所有引數型別
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); // 執行沒有入口引數的方法
}else if("publicMethod".equals(method.getName())) {
System.out.println("回傳值為:"+ method.invoke(demo, 168)); // 執行方法
}else if("protectedMethod".equals(method.getName())) {
System.out.println("回傳值為:"+ method.invoke(demo, "7", 5)); // 執行方法
}else {
Object[] parameters = new Object[] { new String[] {"M", "W", "Q" } }; // 定義二維陣列
System.out.println("回傳值為:"+ method.invoke(demo, parameters));
}
}catch(Exception e) {
System.out.println("在執行方法時拋出例外,"
+ "下面執行setAccessible()方法!");
method.setAccessible(true); // 設定為允許訪問
isTurn = true;
}
}
System.out.println();
}
}
}
/*輸出結果:
名稱為:publicMethod
是否允許帶有可變數量的引數:false
入口引數型別依次為:
int
回傳值型別為:int
可能拋出的例外型別有:
執行publicMethod()方法
回傳值為:16800
名稱為:staitcMethod
是否允許帶有可變數量的引數:false
入口引數型別依次為:
回傳值型別為:void
可能拋出的例外型別有:
執行staitcMethod()方法
名稱為:protectedMethod
是否允許帶有可變數量的引數:false
入口引數型別依次為:
class java.lang.String
int
回傳值型別為:int
可能拋出的例外型別有:
class java.lang.NumberFormatException
執行protectedMethod()方法
回傳值為:12
名稱為:privateMethod
是否允許帶有可變數量的引數:true
入口引數型別依次為:
class [Ljava.lang.String;
回傳值型別為:class java.lang.String
可能拋出的例外型別有:
在執行方法時拋出例外,下面執行setAccessible()方法!
執行privateMethod()方法
回傳值為:
*/
二、使用Annotation功能
1、定義Annotation型別
在定義Annotation型別時,也需要用到用來定義介面的interface關鍵字,不過需要在interface關鍵字前加一個“@”符號,即定義Annotation型別的關鍵字為@interface,這個關鍵字的隱含意思是繼承了java.lang.annotation.Annotation介面,
public @interface NoMemberAnnotation{
String value();
}
@interface:宣告關鍵字,
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) // 用于構造方法
@Retention(RetentionPolicy.RUNTIME) // 在運行時加載Annotation到JVM中
public @interface Constructor_Annotation{
String value() default "默認構造方法"; // 定義一個具有默認值的String型成員
}
②定義一個來注釋欄位、方法和引數的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}) // 用于欄位、方法和引數
@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對構造方法、欄位、方法和引數進行注釋,
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("立即初始化構造方法")
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,那么在運行程式時通過反射就可以獲取到相關的Annotation資訊,如獲取構造方法、欄位和方法的Annotation資訊,
聯合以上的定義并使用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("------ 構造方法的描述如下 ------");
Constructor[] declaredConstructors = recordC
.getDeclaredConstructors(); // 獲得所有構造方法
for (int i = 0; i < declaredConstructors.length; i++) {
Constructor constructor = declaredConstructors[i]; // 遍歷構造方法
// 查看是否具有指定型別的注釋
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(); // 獲得引數的注釋
for (int j = 0; j < parameterAnnotations.length; j++) {
// 獲得指定引數注釋的長度
int length = parameterAnnotations[j].length;
if (length == 0) // 如果長度為0則表示沒有為該引數添加注釋
System.out.println(" 未添加Annotation的引數");
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()); // 獲得引數描述
System.out.println(" " + pa.type()); // 獲得引數型別
}
}
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(); // 獲得引數的注釋
for (int j = 0; j < parameterAnnotations.length; j++) {
int length = parameterAnnotations[j].length; // 獲得指定引數注釋的長度
if (length == 0) // 如果長度為0表示沒有為該引數添加注釋
System.out.println(" 未添加Annotation的引數");
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()); // 獲得引數的描述
System.out.println(" " + pa.type()); // 獲得引數的型別
}
}
System.out.println();
}
}
}
/*輸出結果:
------ 構造方法的描述如下 ------
默認構造方法
立即初始化構造方法
編號 int
姓名 class java.lang.String
-------- 欄位的描述如下 --------
編號 int
姓名 class java.lang.String
-------- 方法的描述如下 --------
獲得姓名
class java.lang.String
設定姓名
void
姓名 class java.lang.String
獲得編號
int
設定編號
void
編號 int
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/355325.html
標籤:java
