主要功能,拦截javaBean的方法,
首先创建一个拦截类,实现MethodInterceptor接口。
/**
*
*/
package org.interceptor;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* 创建人:HF
*
* 创建日期:Jan 15, 2013
* 文件名称:org.interceptor.org.Interceptor
* @version 1.1
* --------------修改记录说明----------------------
* 修改时间:
* 修改内容:
* 修改原因:
* 修改人:
* 修改后版本:
*/
public class LazyInitializer implements MethodInterceptor {
public static Object createBean(Class<?> clazz){
Enhancer enhancer = new Enhancer() ;
enhancer.setSuperclass(clazz) ;
enhancer.setCallback( new LazyInitializer() ) ;
return enhancer.create() ;
}
@Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
return proxy.invokeSuper(obj , args ) ;
}
}
下面可以创建javabean类:
package com.entity;
import com.enums.Sex;
public class User {
/**
*
*/
private static final long serialVersionUID = -5712249899395165324L;
private String name ;
private Sex sex ;
private Double weight ;
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
public String getName() {
return name ;
}
public Sex getSex() {
return sex ;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @param sex the sex to set
*/
public void setSex(Sex sex) {
this.sex = sex;
}
}
动态创建拦截类:
import org.interceptor.LazyInitializer;
import com.entity.User;
public class Test {
public static void main(String[] args)throws Exception {
User user = (User) LazyInitializer.createBean(User.class) ;
user.setName("张三") ;
}
}
资源地址:http://download.youkuaiyun.com/detail/hfmbook/4997876