Home  >  Article  >  Java  >  Detailed introduction to dynamic proxy and reflection mechanism in Java (code example)

Detailed introduction to dynamic proxy and reflection mechanism in Java (code example)

不言
不言forward
2019-01-24 11:03:135480browse

This article brings you a detailed introduction (code example) about dynamic proxy and reflection mechanisms in Java. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Reflection mechanism

A basic function provided by the Java language. Through reflection, we can operate this class or object, such as obtaining the methods, attributes and Construction methods, etc.

Dynamic proxy: divided into JDK dynamic proxy and cglib dynamic proxy (dynamic proxy in spring).

Static proxy

The relationship between the agent and the agent is determined in advance (during compilation). That is to say, if the agent class is determined before the program is run, Already exist, this situation is called static proxy

Dynamic proxy

The proxy class is created when the program is running. In other words, the proxy class is not defined in the Java code, but is dynamically generated during runtime based on our "instructions" in the Java code.

The advantage of dynamic proxy over static proxy is:

Dynamic proxy can easily handle (invoke) the functions of the proxy class uniformly, instead of modifying each function. A proxy class function, more flexible and extensible.

JDK's dynamic proxy (depends on the interface)

In Java's dynamic proxy mechanism, there are two important classes or interfaces, one is the InvocationHandler interface, and the other is One is the Proxy class.

The InvocationHandler interface is implemented for the dynamic proxy class and is responsible for processing the operations of the proxy object.

The Proxy class is used to create dynamic proxy class instance objects. Only when this object is obtained can the required calls be made. Agent method.

The proxy class of the dynamic proxy is modified on the static proxy class, the dynamic proxy class implements the InvocationHandler interface, and overrides the Invoke method. The Invoke method is executed through the incoming proxy class method and parameters.

The following examples:

public interface AppService {
	void createApp(String name);
	void deleteApp(String name);
}
//代理类(比如微商代理)
public class AppServiceImpl implements AppService{

	@Override
	public void createApp(String name) {
		System.out.print("App["+name+"] has been created.");
	}

	@Override
	public void deleteApp(String name) {
		System.out.print("App["+name+"] has been delete.");
	}
}

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class LoggerInterceptor implements InvocationHandler {
    private Object target; //委托类(被代理类)的实例,比如厂家
    public LoggerInterceptor(Object target){  
        this.target = target;  
    }  
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
		System.out.println("Entered "+target.getClass().getName()+"-"+method.getName()+",with arguments{"+args[0]+"}");  
        Object result = method.invoke(target, args);
       //调用目标对象的方法  (调用厂家的方法(createApp)及参数(Kevin Test))
        System.out.println("Before return:"+result);  
        return result;  
	}

}
import java.lang.reflect.Proxy;

public class test {

public static void main(String[] args) {
    AppService target = new AppServiceImpl();//生成目标对象 (代理类的对象)
    //接下来创建代理对象 
    AppService proxy = (AppService) Proxy.newProxyInstance( 
    target.getClass().getClassLoader(), 
    target.getClass().getInterfaces(), new LoggerInterceptor(target)); 
    proxy.createApp("Kevin Test1"); 
    proxy.deleteApp("Kevin Test2"); 
  }

}/**
* 1、jdk的动态代理实现方式是依赖于接口的,首先使用接口来定义好操作规范。
* 2、通过proxy类产生的代理对象调用被代理对象的操作。
* 3、而这个操作又被分发给InvocationHandler接口的invoke方法具体执行
* 
* 在java的动态代理机制中,有两个重要的类或接口,一个是InvocationHandler接口、另一个则是 Proxy类,这个类和接口是实现我们动态代理所必须用到的。
InvocationHandler接口是给动态代理类实现的,负责处理被代理对象的操作的,而Proxy是用来创建动态代理类实例对象的,因为只有得到了这个对象我们才能调用那些需要代理的方法。
* 
* 此方法的参数含义如下 
proxy:代表动态代理对象 
method:代表正在执行的方法 
args:代表当前执行方法传入的实参 
返回值:表示当前执行方法的返回值
* 
* 如上:
* 使用了Proxy类的newProxyInstance方法生成代理对象,然后用这个对象去调用createApp()和deleteApp()方法,
* 其实系统会将这2个方法分发给invoke()方法区执行。其中proxy对象的类是系统帮我们动态创建了,其实实现了我们的业务接口AppService
* 
*/

cglib dynamic proxy (inheritance method)

MethodInterceptor is used in cglib dynamic proxy to achieve dynamics Agent class.

In the interceptor MethodInterceptor, the proxy method is called by the InvokSuper method of MethodProxy.

The MethodProxy class generates proxy methods and signatures of proxy methods.

The difference between JDK dynamic proxy and Cglib dynamic proxy:

1. JDK dynamic proxy implements the interface of the proxy object, while Cglib inherits the proxy object.

2. Because Cglib is an inheritance mechanism, it cannot proxy methods modified by final.

3. Both JDK and Cglib produce bytecodes during runtime. JDK directly writes class bytecodes, while Cglib uses the ASM framework to write class bytecodes; cglib agent implementation is more complex, and generating agent classes is better than JDK low efficiency.

4. JDK calls proxy methods through the reflection implementation mechanism, while cglib calls methods directly through the Fashclass mechanism, which is more efficient.

Fastcalss mechanism:

Generate a class for the proxy class and the proxy class. This class will assign an index to the method of the proxy class or the proxy class.

This index is used as an input parameter, and Fashclass can directly locate the method to be called and call it directly. This eliminates the need for reflection calls, so it is highly efficient.

The above is the detailed content of Detailed introduction to dynamic proxy and reflection mechanism in Java (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete
Previous article:what is eclipseNext article:what is eclipse