当前位置:首页 > 开发 > 编程语言 > Java > 正文

java 动态代理简单实现

发表于: 2014-08-18   作者:antlove   来源:转载   浏览:
摘要: dynamicproxy.service.HelloService package dynamicproxy.service; public interface HelloService { public void sayHello(); }   dynamicproxy.service.impl.HelloServiceImpl package dynamicp

dynamicproxy.service.HelloService

package dynamicproxy.service;

public interface HelloService {
	public void sayHello();
}

 

dynamicproxy.service.impl.HelloServiceImpl

package dynamicproxy.service.impl;

import dynamicproxy.service.HelloService;

public class HelloServiceImpl implements HelloService {

	@Override
	public void sayHello() {
		System.out.println("hello everyone ... ");

	}

}

 

dynamicproxy.handler.LogHandler

package dynamicproxy.handler;

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

public class LogHandler implements InvocationHandler {

	private Object target = null;
	
	public LogHandler(Object target) {
		this.target = target;
	}

	private void doBefore(){
		System.out.println("do before ... ");
	}
	
	private void doAfter(){
		System.out.println("do after ... ");
	}
	
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
	
		doBefore();
		
		Object res = method.invoke(target, args);
		
		doAfter();
		
		return res;
	}

}

 

dynamicproxy.test.Main

package dynamicproxy.test;

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

import dynamicproxy.handler.LogHandler;
import dynamicproxy.service.HelloService;
import dynamicproxy.service.impl.HelloServiceImpl;

public class Main {

	public static void main(String[] args) {
		HelloService target = new HelloServiceImpl();
		
		InvocationHandler handler = new LogHandler(target);
		
		HelloService helloService = (HelloService) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
		
		helloService.sayHello();

	}

}

 

 

java 动态代理简单实现

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号