一.什麼是java反射
能通過一個類的名稱創建這個類的對象,並且使用類中的方法和屬性
二.爲什麼會有發射?使用反射有什麼好處?
1.降低程序的耦合程度
2.用作框架:用框架是需要讀取配置文件,通過配置文件,讀取要用到的類的名稱,然後通過反射得到他的方法,
爲什麼框架要用反射呢?因爲框架設計者不知道你在用這個框架的時候用到什麼jar包,什麼類,所以要用到反射
com.oracle
ojdbc14
10.2.0.4.0
三.獲取類的字節碼
有三種方法:
1.Class<?> aClass = Class.forName(“reflection.Factory”);
2.Class stringClass = String.class;
3.Class<? extends String> aClass1 = new String().getClass();
可以通過字節碼,創建一個這個類的對象
四.上代碼
package reflection;
public class Factory {
public String sa = "adjahd";
private Factory reflection;
private int i = 3;
public Factory(){
System.out.println("Factory");
}
public Factory(String s){
System.out.println(s);
}
private Factory(int i2){
System.out.println(i2);
}
public static IBaoCaiMing getZhengxiongzhang(){
return new ZhengXiongZhang();
}
public static IBaoCaiMing getZhengyanggao(){
return new ZhengYangGao();
}
public void prient(){
System.out.println("這是方法");
}
private String gest(String saa){
System.out.println(saa);
return "我是返回值";
}
}
package reflection;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ClassDome {
@Test
public void test1() throws Exception{
//加載類 得到的是類的字節碼 三種方式
Class<?> aClass = Class.forName("reflection.Factory");
Class<String> stringClass = String.class;
Class<? extends String> aClass1 = new String().getClass();
System.out.println("--------------------構造函數----------------------");
//獲取類的public構造函數,創建出對象
Constructor constructor = aClass.getConstructor(String.class);
Factory aa = (Factory) constructor.newInstance("jasfhja");
//獲取類的private的構造函數,
Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(int.class);
declaredConstructor.setAccessible(true);//暴力訪問
Factory o = (Factory) declaredConstructor.newInstance(3);
//只適用於無參的構造函數
Factory o1 = (Factory) aClass.newInstance();
System.out.println("--------------------屬性----------------------");
//獲取類的public屬性
Field sa = aClass.getField("sa");
Object field = sa.get(o);
System.out.println(field);
//獲取類的private的屬性
Field reflection = aClass.getDeclaredField("reflection");
reflection.setAccessible(true);
Factory field1 = (Factory) reflection.get(o);
System.out.println(field1); //這只是引用並沒有賦值
reflection.set(o,new Factory()); //給reflection屬性賦值
System.out.println("--------------------方法----------------------");
//獲取類的public方法
Method prient = aClass.getMethod("prient", null);
prient.invoke(o,null); //參數是一個對象 和 可變參數
//獲取類的private方法、並獲取返回值
Method gest = aClass.getDeclaredMethod("gest", String.class);
gest.setAccessible(true);
String mes = (String) gest.invoke(o, "mes");
System.out.println(mes);
}
}
運行結果
--------------------構造函數----------------------
jasfhja
3
Factory
--------------------屬性----------------------
adjahd
null
Factory
--------------------方法----------------------
這是方法
mes
我是返回值