涉及 类加载机制
RefectionData
ReflectionFactory
参考:
java反射原理
- Reflection API
Array 类 提供动态地生成和访问 JAVA 数组的方法。
Constructor 类 提供一个类的构造函数的信息以及访问类的构造函数的接口。
Field 类 提供一个类的域的信息以及访问类的域的接口。
Method 类 提供一个类的方法的信息以及访问类的方法的接口。
Modifier类 提供了 static 方法和常量,对类和成员访问修饰符进行解码。
Proxy 类 提供动态地生成代理类和类实例的静态方法。
- 获取class对象
A.class
a.getClass
Class.forName(A)
- constructor :考虑有参无参
Constructor constructor2 = reflectClass.getConstructor(String.class,int.class);
reflectClass.getConstructors();
reflectClass.getDeclaredConstructors();
- 实例化
无参 reflectClass.newInstance();
有参 constructor2.newInstance("hello",1);
- field
数组 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();
-动态创建代理类
在java中有三种类加载器。
1)BootstrapClassLoader此加载器采用c++编写,一般开发中很少见。
2)ExtensionClassLoader用来进行扩展类的加载,一般对应的是jre\lib\ext目录中的类
3)AppClassLoader 加载 classpath 指定的类,是最常用的加载器。同时也是java 中默认的加载器。 如果想要完成动态代理,首先需要定义一个 InvocationHandler接口的子类,以完成代理的具体操作。
public interface Subject {
String say(String name,int age);
String ask(String name , int age);
}
// 具体实现类
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() 改变其实现 其他不改变
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