动态继承一个类/抽象类(不是接口),(动态实现接口参照https://gist.github.com/gexiangdong/f7536a8d86a631b1c391acf13d334a90 )
此实现需要cglib, pom中增加依赖
1 2 3 4 5
| <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.2.10</version> </dependency>
|
实现代码如下:
待创建的父类,可以是抽象类
1 2 3 4 5 6 7 8 9 10 11 12
|
public class MyClass { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
|
动态创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| 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;
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())) {
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)); } }
|