您的位置:首页 > 职场人生

黑马程序员 Java自学总结二十 Java高新技术第三天

2013-08-09 15:38 555 查看
------ ASP.Net+Android+IO开发.Net培训期待与您交流! ------



总结内容来源于张孝祥老师的Java高新技术
代理

代理的概念与作用

为其他对象提供一种代理以控制对这个对象的访问 . 在某些情况下,一个客户不想或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用.

代理模式简单示例

[java] view
plaincopy

//目标类:

class A

{

void sayHello()

{

System.out.println("hello itcast");

}

}

// 代理类:

AProxy

{

void sayHello()

{

starttime;

A.sayHello();

endTime;

}

}

程序中的代理

1.要为已存在的多个具有相同接口的目标类的各个方法增加一系列的系统功能,例如,异常处理,日志、计算方法等的运行时间、事务管理等等,你如何做?

2.编写一个与目标类具有相同接口的代理类,代理类的每个方法调用目标类的相同方法,并在调用方法时加上系统功能的代码。

3.如果采用工厂模式和配置文件的方式进行管理,则不需要修改客户端程序,在配置文件中配置是使用目标类还是代理类,这样以后很容易切换。譬如,想要日志功能时就配置代理类,否则配置目标类,这样增加系统功能很容易。以后运行一段时间后,又想去掉系统功能也很容易。

代理分为两种:静态代理和动态代理。

<AOP>

1.系统中存在交叉业务,一个交叉业务就是要切入到系统中的一个方法。

2.交叉业务的房产问题即为面向方面的编程(AOP,Aspect oriented program),AOP的目标就是要使交叉业务模块化,可以采用将切面代码移动到原始方法的周围,这与直接在方法中编程切面代码的运行效果是一样的。

3.使用代理技术正好可以解决这种问题,代理是实现AOP功能的核心和关键技术。

动态代理技术(JVM动态代理和CGLIB库动态代理)

1.要为系统中的各种接口的类增加代理功能,那将需要太多的代理类,全部采用静态代理方式,将是一件非常麻烦的事情。(引出动态代理)

2.JVM可以在运行期动态生成出类的字节码,这种动态生成的类往往被用作 代理类 ,即动态代理类。

3.JVM生成的动态类必须具有一个或多个接口,所以,JVM生成的动态类(Proxy)只能用作具有相同接口的目标类的代理。

4.CGLIB库(一个开源库)可以动态生成一个类的子类,一个类的子类也可以用作该类的代理,所以,如果要为一个没有实现接口的 类生成动态代理类,可以使用CGLIB库。

代理类的各个方法中通除了要调用目标的相应方法和对外返回目标返回的结果外,还可以在代理方法中的如下 四个位置加上系统功能代码:

1.在调用目标方法之前

2.在调用目标方法之后

3.在调用目标方法之前或之后

4.在处理目标方法异常的catch块中。

创JVM动态代理的三种方法:

[java] view
plaincopy

package study.day3;

import java.lang.reflect.Constructor;

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;

import java.util.ArrayList;

import java.util.Collection;

public class ProxytTest {

public static void main(String[] args) throws Exception {

Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);

System.out.println(clazzProxy.getName());

//获取代理类的所有构造方法

Constructor[] constructors = clazzProxy.getConstructors();

System.out.println("--------------------constructors--------------------");

for(Constructor constructor : constructors){

String constructorName = constructor.getName();

System.out.print(constructorName);

StringBuilder sb = new StringBuilder();

sb.append("(");

Class[] clazzParams = constructor.getParameterTypes();

for(Class clazzParam : clazzParams){

sb.append(clazzParam.getName()+",");

}

if(clazzParams != null && clazzParams.length != 0)

sb.deleteCharAt(sb.length()-1);

sb.append(")");

System.out.println(sb.toString());

}

//获取代理类的所有方法

Method[] methods = clazzProxy.getMethods();

System.out.println("--------------------methods--------------------");

for(Method method : methods){

String constructorName = method.getName();

System.out.print(constructorName);

StringBuilder sb = new StringBuilder();

sb.append("(");

Class[] clazzParams = method.getParameterTypes();

for(Class clazzParam : clazzParams){

sb.append(clazzParam.getName()+",");

}

if(clazzParams != null && clazzParams.length != 0)

sb.deleteCharAt(sb.length()-1);

sb.append(")");

System.out.println(sb.toString());

}

//获取代理类的实例对象

System.out.println("--------------------instance--------------------");

Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class);

//获取代理类对象的方法一 : 用代理类的构造方法类和实现了接口的类

class MyInvocationHandler implements InvocationHandler{

@Override

public Object invoke(Object proxy, Method method, Object[] args)

throws Throwable {

// TODO Auto-generated method stub

return null;

}

}

Collection proxy1 = (Collection)constructor.newInstance(new MyInvocationHandler());

//获取代理类对象的方法二 : 用代理类的构造方法类和匿名内部类

Collection proxy2 = (Collection)constructor.newInstance(new InvocationHandler(){

@Override

public Object invoke(Object proxy, Method method, Object[] args)

throws Throwable {

return null;

}});

//获取代理类对象的方法三 : 用Proxy的newProxyInstance方法

Collection proxy3 = (Collection)Proxy.newProxyInstance(

Collection.class.getClassLoader(),

new Class[]{Cellection.class},

new InvocationHandler(){

ArrayList target = new ArrayList();

@Override

public Object invoke(Object proxy, Method method, Object[] args)

throws Throwable {

long before = System.currentTimeMillis();

Object reValue = method.invoke(target, args);

long after = System.currentTimeMillis();

System.out.println(method.getName()+"---runtime---"+(after-before));

return reValue;

}

}

);

}

}

注意:从Object继承来的方法 , 只有toString , hashCode , equals , 调用时委托给InvocationHandler,其他的方法Proxy自己都有实现.

使动态生成的类成为任意目标的代理

动态代理类的骨架使用Proxy.newProxyInstance()方法生成,执行时再传入两个参数:要代理的目标target和增加的系统功能的封装对象(advice),再把它们封装成一个方法.

[java] view
plaincopy

//advise实现的接口

package study.day3;

import java.lang.reflect.Method;

public interface Advise {

void before(Method method);

void after(Method method);

}

//advise

package study.day3;

import java.lang.reflect.Method;

public class MyAdvise implements Advise {

long before = 0;

public void before(Method method) {

System.out.println("努力进黑马");

before = System.currentTimeMillis();

}

public void after(Method method) {

System.out.println("学习学习再学习");

long after = System.currentTimeMillis();

System.out.println(method.getName()+"---runtime---"+(after-before));

}

}

package study.day3;

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Proxy;

import java.util.ArrayList;

import java.util.Collection;

public class ProxytTest {

public static void main(String[] args) throws Exception {

ArrayList target = new ArrayList();

Advise advise = new MyAdvise();

//调用方法

Collection proxy4 = (Collection) getProxy(target,advise);

//封装的方法

private static Object getProxy(final Object target,final Advise advise) {

Object proxy4 = Proxy.newProxyInstance(

target.getClass().getClassLoader(),

target.getClass().getInterfaces(),

new InvocationHandler(){

@Override

public Object invoke(Object proxy, Method method, Object[] args)

throws Throwable {

/*long before = System.currentTimeMillis();

Object reValue = method.invoke(target, args);

long after = System.currentTimeMillis();

System.out.println(method.getName()+"---runtime---"+(after-before));

return reValue;*/

advise.before(method);

Object reValue = method.invoke(target, args);

advise.after(method);

return reValue;

}

}

);

return proxy3;

}

}

实现可配置的AOP(面向方面)框架

需求:Bean工厂BeanFactory负责创建配置文件中读取出的目标类的Bean , 如果读取到的是BeanFactoryProxy则调用BeanFactoryProxy的getProxy方法 , 返回目标类的代理

代码:

[java] view
plaincopy

package com.study.day3.aopframework;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.Collection;

public class AopFranmeworkTest {

public static void main(String[] args) throws Exception {

InputStream is = AopFranmeworkTest.class.getResourceAsStream("config.properties");

Collection bean = (Collection) new BeanFactory(is).getBean("xxx");

System.out.println(bean.getClass().getName());

System.out.println(bean.getClass().getMethod("add", Object.class)

.getName());

bean.add("123");

System.out.println(bean.size());

}

}

package com.study.day3.aopframework;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

import com.study.day3.Advise;

//BeanFactory类,用于返回Bean,如果配置文件中是读取的是BeanFactoryProxy,则调用BeanFactoryProxy返回代理

public class BeanFactory {

Properties props = new Properties();

BeanFactory(InputStream is) throws Exception{

props.load(is);

}

public Object getBean(String name) throws Exception{

String className = props.getProperty(name);

Class clazz = Class.forName(className);

Object bean = clazz.newInstance();

if(bean instanceof BeanFactoryProxy){

BeanFactoryProxy beanFactoryProxy = (BeanFactoryProxy)bean;

Advise advise = (Advise)Class.forName(props.getProperty(name+".advise")).newInstance();

Object target = Class.forName(props.getProperty(name+".target")).newInstance();

//System.out.println(target.getClass().getName());

beanFactoryProxy.setAdvise(advise);

beanFactoryProxy.setTarget(target);

return beanFactoryProxy.getProxy();

}

return bean;

}

}

package com.study.day3.aopframework;

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;

import com.study.day3.Advise;

import com.study.day3.MyAdvise;

//BeanFactoryProxy类,用于返回代理

public class BeanFactoryProxy {

private Advise advise = null;

private Object target = null;

public void setAdvise(Advise advise) {

this.advise = advise;

}

public void setTarget(Object target) {

this.target = target;

}

public Object getProxy() {

Object proxy = Proxy.newProxyInstance(

target.getClass().getClassLoader(),

target.getClass().getInterfaces(),

new InvocationHandler() {

@Override

public Object invoke(Object proxy, Method method, Object[] args)

throws Throwable {

Advise advise = new MyAdvise();

advise.before(method);

Object reValue = method.invoke(target, args);

advise.after(method);

return reValue;

}

});

return proxy;

}

}

package com.study.day3;

import java.lang.reflect.Method;

public interface Advise {

void before(Method method);

void after(Method method);

}

package com.study.day3;

import java.lang.reflect.Method;

public class MyAdvise implements Advise {

long before = 0;

public void before(Method method) {

System.out.println("努力进黑马");

before = System.currentTimeMillis();

}

public void after(Method method) {

System.out.println("学习学习再学习");

long after = System.currentTimeMillis();

System.out.println(method.getName()+"---runtime---"+(after-before));

}

}

------ ASP.Net+Android+IO开发.Net培训期待与您交流! ------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: