java动态代理例子

Service.java

public interface Service 
{     
    public void add(String aa); 
    public String pay(String aa); 
} 

 ServiceImpl.java

public class ServiceImpl implements Service 
{ 
    public void add(String aa) 
    { 
        System.out.println("添加用户!"+aa); 
         
    } 
    
    @Override
    public String pay(String aa) {
    	System.out.println("玩玩!"+aa); 
    	return aa ;
    }
} 

 ServiceHandle.java

public class ServiceHandle implements InvocationHandler 
{ 
    private Object s; 
     
    public ServiceHandle(Object s) 
    { 
        this.s = s; 
    }
    
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
        System.out.println("服务开始,做一些前置操作!"); 
        //invoke表示对带有指定参数的指定对象调用由此 Method 对象表示的底层方法 
        if(method.getName().equals("pay")){
        	System.out.println("调用的方法: "+method.getName());
        }
        Object result=method.invoke(s, args); 
        System.out.println("服务结束,做一些后续操作!"); 
        return result; 
    } 
} 

 ServiceProxy.java

public class ServiceProxy implements Service 
{ 
    private Service service; 
    public ServiceProxy(Service service) 
    { 
        super(); 
        this.service = service; 
    } 
    public void add(String aa) 
    { 
        System.out.println("服务开始"); 
        service.add(""); 
        System.out.println("服务结束"); 
    } 
    @Override
    public String pay(String aa) {
		return aa;
    	// TODO Auto-generated method stub
    	
    }
} 

 TestMain.java

public class TestMain {
	public static void main(String[] args) 
	    { 
	        Service service=new ServiceImpl(); 
	        InvocationHandler handler=new ServiceHandle(service); 
	        Service s=(Service) Proxy.newProxyInstance(service.getClass().getClassLoader(), service.getClass().getInterfaces(), handler); 
//	        service.add("235");
	        
	        s.add("123"); 
	        System.out.println(s.pay("job"));
	    } 
	
	
}

 

你可能感兴趣的:(java动态代理例子)