Skip to content

Instantly share code, notes, and snippets.

@gexiangdong
Last active February 13, 2019 10:44
Show Gist options
  • Select an option

  • Save gexiangdong/599b58566e349be40d99ee02877eb985 to your computer and use it in GitHub Desktop.

Select an option

Save gexiangdong/599b58566e349be40d99ee02877eb985 to your computer and use it in GitHub Desktop.
动态继承一个类/抽象类(不是接口),(动态实现接口参照https://gist.github.com/gexiangdong/f7536a8d86a631b1c391acf13d334a90
/**
* 被创建的类的例子
*/
public class MyClass {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* 使用CGLIB动态生成一个类的子类的例子
*/
public class MyClassProxy {
public static void main(String[] argvs) throws Exception{
MyClass mc = createDefaultImplementation(MyClass.class);
mc.setName("waytt");
System.out.println(mc.getName());
}
public static <A> A createDefaultImplementation(Class<A> abstractClass) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(abstractClass);
enhancer.setCallback(new MethodInterceptor() {
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("MethodInterceptor.intercept(proxy, " + method.getName() + ",...)");
if (!Modifier.isAbstract(method.getModifiers())) {
//not abstract method, 可调用类的方法并返回
return methodProxy.invokeSuper(proxy, args);
} else {
// 抽象方法,不能执行父类的方法了,需要自己构建一个返回值
System.out.println("abstract method....");
Class type = method.getReturnType();
// 生成返回值
return null;
}
}
});
return (A) enhancer.create();
}
public static <A> A createDefaultImplementation(String className) throws ClassNotFoundException{
return (A) createDefaultImplementation(Class.forName(className));
}
}
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.10</version>
</dependency>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment