Java反射 1-1訪問構造方法
阿新 • • 發佈:2021-01-31
Java反射
1-1訪問構造方法
思路如下:
- 建立Class類物件,以獲得constructor[ ]
迴圈或流訪問每一個構造方法:獲得修飾符、異常資訊型別、入口引數型別 - 如果是if i==2,此時構造方法修飾符是private,需要用setAccessible方法繞過系統許可權,根據constructor1.newinstance()建立物件。
Class exampleC=Example01.class;//先獲得Example01對應的Class類
//獲得所有構造方法
Constructor[] constructor= exampleC.getDeclaredConstructors();
for(int i=0;i<constructor.length;i++) {
Constructor constructor1 = constructor[i];
System.out.println("檢視是否允許帶有可變引數型別的變數:" + constructor1.isVarArgs());
System.out.println("該構造方法的入口引數型別依次為");
Class[ ] parameterTypes = constructor1.getParameterTypes();//獲取入口引數型別
for (Class c : parameterTypes) {
System.out.println("" + c);
}
//獲得所有可能丟擲的異常資訊型別
System.out.println("獲得所有可能丟擲的異常型別");
Class[] exception = constructor1. getExceptionTypes();
for (Class c : exception) {
System.out.println("" + c);
}
Example01 example01 = null;
while (example01 == null) {
try {
if (i == 2) {//通過執行沒有引數的構造方法建立物件
example01 = (Example01) constructor1.newInstance();
} else if (i == 1) {
example01 = (Example01) constructor1.newInstance("7", 5);
} else {
//可變引數
String[][] parameters = {{"100", "200", "300"}};
example01 = (Example01) constructor1.newInstance(parameters);
}
}catch(Exception e){
System.out.println("在建立物件時丟擲異常,下面執行setAcessable");
constructor1.setAccessible(true);
e.printStackTrace();
}
}
}
其中Example01類程式碼如下:
public class Example01 {
String s;
int i,i2,i3;
public Example01(){
}
private Example01(String s,int i){
this.s=s;
this.i=i;
}
public Example01(String... strings) {//當新增引數的時候,一定要將其新增成String[][],因為JVM本身此時不會將其package.
if(strings.length>0){
i=Integer.valueOf(strings[0]);
}
else if(strings.length>1){
i2=Integer.valueOf(strings[1]);
}
else if(strings.length>2){
i3=Integer.valueOf(strings[2]);
}
}
public void print(){
System.out.println("s="+s);
System.out.println("i="+i);
System.out.println("i2="+i2);
System.out.println("i3="+i3);
}
}
其中需要注意的問題是:
- String… strings代表數量可變引數,在呼叫該構造方法時,需將其包裝成String[][],否則會報wrong number of arguments的錯誤。
- 具體解釋如下