Java's radiation mechanism: When the program is running, the program has the ability to obtain all the methods and attributes of a class; and for any object, you can call any of its methods or obtain its attributes
Popular analysis: java files need to be compiled into .class files to be loaded and used by jvm. The .class data of the object is Class<T> in jvm; if we can get this Class<T> object, we can get the Class<T > Corresponding object type, and the method and attribute value declared in the type; you can also create the corresponding type object according to Class<T>, and manipulate the object in turn through Field and Method
Introduction to java related classes
Class name
description
Class<T>
An entity representing a class, representing a class or interface in a running Java application
Field
Class member variables (member variables are also called class attributes)
public Class<Example>getExampleByInstance(){
Example example =newExample();// getClass是Object类里面的方法;《?》 是通配符
Class<?> clazz = example.getClass();return(Class<Example>)clazz;}
3 Get the class with the specified class name in the full path through Class.forName
//根据传递的参数创建类的对象:initargs 构造方法参数public T newInstance(Object... initargs)
1 Create objects based on class
//方式一 clazz.newInstance()
Class<Example> clazz = Example.class;
Example example = clazz.newInstance();//方式二 先获取再由Constructor:clazz.getConstructors()/getConstructor(...) //再由Constructor.newInstance 方法构造对象-----------------------------------------publicclassExample{
privateint value;publicExample(){
}// 如果只声明有参构造函数,clazz.newInstance()会报错publicExample(Integer value){
this.value = value;}staticpublicvoidmain(String[] args)throws Exception{
Class<Example> clazz = Example.class;//根据指定构造函数参数获取Constructor
Constructor<Example> constructor = clazz.getConstructor(Integer.class);
Example example = constructor.newInstance(100);
System.out.println(example.value);}}
2 Obtain the Field from the class and manipulate the attributes of the instance
publicclassExample{
privateint value , count;staticpublicvoidmain(String[] args)throws Exception{
Class<Example> clazz = Example.class;//获取所有的属性,getField只能获取public的属性
Field[] fs = clazz.getDeclaredFields();//根据名称获取指定 Field
Field value = clazz.getDeclaredField("value");
Example example = clazz.newInstance();//使用反射机制可以打破封装性,导致了java对象的属性不安全
value.setAccessible(true);//setAccessible(true)让private的参数可赋值操作//由Field反过去设置example的值
value.set(example,100);
System.out.println(example.value);}}
3 Get Method by class and call instance method by reflection
1 Dynamic expansion: It is assumed that there is the same group of classes that implement the same interface, and the loading method of the class is not limited. When we need the function that a specific class implements, just load the .class file and get the corresponding Class<T> object. The object instance can be instantiated by Class or Constructor; according to the interface definition, a certain method in Class<T> can be obtained, and the function method can be called with instance
2 Spring's IOC is based on the reflection mechanism
3 Dynamic proxy of JDK
Reflection and JDK dynamic proxy
A Proxy class and an InvocationHandler interface are provided under the java.lang.reflect package of Java. JDK dynamic proxy class or dynamic proxy object can be generated through this class and interface
The dynamic proxy of JDK is implemented by Proxy and InvocationHandler; the proxy object must implement an interface. The proxy object is generated by the Proxy and can be converted to the implementation class object OBJ of the interface interface. When the OBJ method is called, InvocationHandler.invoke will be triggered, and the parameters are the proxy object , the Method object , and the parameters required by the method in turn . You can add extended logic to the invoke method, such as logging operations; and you can use reflection technology to call the proxy object method in the invoke method
Example
publicclassExampleFactory<T>implementsInvocationHandler{
private T target;public T bind(T obj){
target = obj;return(T)Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),this);}@Overridepublic Object invoke(Object o, Method method, Object[] objects)throws Throwable {
//增强逻辑
System.out.println("log start");//反射调用被代理对象方法
Object result = method.invoke(target,objects);
System.out.println("log end");return result;}}-----------publicinterfaceFace{
voidhello(String name);}---------//被代理对象必须实现一个接口,并由接口方法对方提供功能publicclassExampleimplementsFace{
publicvoidhello(String name){
System.out.println(name +" Hello!");}publicstaticvoidmain(String[] args){
//ExampleFactory<Face> 相当于一个中介人
ExampleFactory<Face> exampleProxy=newExampleFactory<>();//example 是代理对象
Face example = exampleProxy.bind(newExample());
example.hello("思婷");}}-----
log start
思婷 Hello!
log end
Welcome refers to the error in the text
Follow the public account and communicate together