java之JDK动态代理

© 版权声明:本文为博主原创文章,转载请注明出处

JDK动态代理:

  JDK动态代理就是在程序运行期间,根据java的反射机制自动的帮我们生成相应的代理类

优势:

  - 1. 业务类只需要关注业务逻辑本身,保证了业务类的重用性

  - 2. 只需一个动态代理类就可以代理很多接口,大大减少了代理类的规模,便于维护

  - 3. 接口变了,动态代理类也不需要任何改动

劣势:

  - 1. 只能代理有接口的类,不能代理一个没有任何接口的类

实例:

1.项目结构

2.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  
  	<modelVersion>4.0.0</modelVersion>

	<groupId>org.proxy</groupId>
	<artifactId>DynamicProxy-JDK</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	
</project>

3.Hello.java

package org.proxy.DynamicProxy_JDK;

/**
 * 接口-抽象角色
 *
 */
public interface Hello {

	void say(String name);
	
}

4.HelloImpl.java

package org.proxy.DynamicProxy_JDK;

/**
 * 接口实现类-真实角色
 *
 */
public class HelloImpl implements Hello {

	public void say(String name) {
		
		System.out.println("Hello!" + name);

	}

}

5.DynamicProxy.java

package org.proxy.DynamicProxy_JDK;

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

/**
 * 代理角色-动态代理类
 *
 */
public class DynamicProxy implements InvocationHandler {

	private Object target;
	
	public DynamicProxy(Object target) {

		this.target = target;
		
	}
	
	@SuppressWarnings("unchecked")
	public <T> T getProxy() {
		
		return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), 
				target.getClass().getInterfaces(), this);
		
	}

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		
		before();
		Object result = method.invoke(target, args);
		after();
		return result;
		
	}
	
	private void before() {
		
		System.out.println("Before");
		
	}
	
	private void after() {
		
		System.out.println("After");
		
	}
    
}

6.TestJDKDynamicProxy.java

package org.proxy.test;

import org.junit.Test;
import org.proxy.DynamicProxy_JDK.DynamicProxy;
import org.proxy.DynamicProxy_JDK.Hello;
import org.proxy.DynamicProxy_JDK.HelloImpl;

public class TestJDKDynamicProxy {

	@Test
	public void testHello() {
		
		Hello hello = new HelloImpl();
		
		DynamicProxy dynamicProxy = new DynamicProxy(hello);
		
		Hello helloProxy = dynamicProxy.getProxy();
		
		helloProxy.say("Jack");
		
	}
	
}

7.效果预览

参考:《架构探险-从零开始写Java Web框架》(黄勇著)

posted @ 2017-06-02 11:30  禁忌夜色153  阅读(239)  评论(0编辑  收藏  举报