涉及 類加載機(jī)制
RefectionData
ReflectionFactory
參考:
java反射原理
- Reflection API
Array 類 提供動(dòng)態(tài)地生成和訪問 JAVA 數(shù)組的方法教沾。
Constructor 類 提供一個(gè)類的構(gòu)造函數(shù)的信息以及訪問類的構(gòu)造函數(shù)的接口。
Field 類 提供一個(gè)類的域的信息以及訪問類的域的接口译断。
Method 類 提供一個(gè)類的方法的信息以及訪問類的方法的接口授翻。
Modifier類 提供了 static 方法和常量,對(duì)類和成員訪問修飾符進(jìn)行解碼。
Proxy 類 提供動(dòng)態(tài)地生成代理類和類實(shí)例的靜態(tài)方法堪唐。
- 獲取class對(duì)象
A.class
a.getClass
Class.forName(A)
- constructor :考慮有參無參
Constructor constructor2 = reflectClass.getConstructor(String.class,int.class);
reflectClass.getConstructors();
reflectClass.getDeclaredConstructors();
- 實(shí)例化
無參 reflectClass.newInstance();
有參 constructor2.newInstance("hello",1);
- field
數(shù)組 reflectClass.getDeclaredFields() 包括公有的 私有的
私有的需要 setAccessible(true)
reflectClass.getFields() 公有的以及父類
reflectClass.getDeclaredField("name");
- method
reflectClass.getDeclaredMethods()
reflectClass.getDeclaredMethod("methodName")
reflectClass.getMethods()
reflectClass.getMethod("methodName")
- 父類(接口)
reflectClass.getInterfaces()
reflectClass.getSuperClass()
- 修飾符
reflectClass.getModifiers();
-動(dòng)態(tài)創(chuàng)建代理類
在java中有三種類加載器巡语。
1)BootstrapClassLoader此加載器采用c++編寫,一般開發(fā)中很少見淮菠。
2)ExtensionClassLoader用來進(jìn)行擴(kuò)展類的加載男公,一般對(duì)應(yīng)的是jre\lib\ext目錄中的類
3)AppClassLoader 加載 classpath 指定的類,是最常用的加載器合陵。同時(shí)也是java 中默認(rèn)的加載器枢赔。 如果想要完成動(dòng)態(tài)代理,首先需要定義一個(gè) InvocationHandler接口的子類拥知,以完成代理的具體操作踏拜。
public interface Subject {
String say(String name,int age);
String ask(String name , int age);
}
// 具體實(shí)現(xiàn)類
public class RealSubject implements Subject {
public String name;
public int age;
@Override
public String say(String name, int age) {
return name+" "+age;
}
@Override
public String ask(String name, int age) {
return "ask: r y name is : "+name+" \t "+" & age is : "+age;
}
}
public class InvovationTest {
public static void demo(){
MyInvocationHandler demo =new MyInvocationHandler();
Subject sub = (Subject)demo.bind(new RealSubject());
Log.d(tag," ask: "+sub.ask("Rollen",28));
String info = sub.say("Rollen",20);
Log.d(tag,"say = "+info);
}
}
class MyInvocationHandler implements InvocationHandler {
private Object obj = null;
public Object bind(Object obj) {
this.obj = obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
Object temp;
// function: say() 改變其實(shí)現(xiàn) 其他不改變
if (TextUtils.equals(methodName,"say")){
temp = " i change the source";
}else {
temp = method.invoke(this.obj, args);
}
return temp;
}
}
log日志:
06-17 22:01:37.194 8311-8311/com.pq.tools D/ppp_: method: ask
06-17 22:01:37.194 8311-8311/com.pq.tools D/ppp_InvocationTest: ask: ask: r y name is : Rollen & age is : 28
06-17 22:01:37.194 8311-8311/com.pq.tools D/ppp_: method: say
06-17 22:01:37.194 8311-8311/com.pq.tools D/ppp_InvocationTest: say = i change the source