I am learn cglib proxy, When I use Person class which declared in the DemoApplication class as the target of super class of enhancer, there will be a error like this.
This is my code
public class DemoApplication {
public static void main(String[] args) {
new DemoApplication();
}
DemoApplication(){
Person person = new Person();
MyMethodInterceptor myMethodInterceptor = new MyMethodInterceptor(person);
person = (Person) myMethodInterceptor.getProxyInstance();
person.say();
}
class Person{
void say(){
System.out.println("I am saying");
}
}
class MyMethodInterceptor implements MethodInterceptor {
Object target;
MyMethodInterceptor(Object target){
this.target = target;
}
Object getProxyInstance(){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(Person.class);
enhancer.setCallback(this);
enhancer.setClassLoader(DemoApplication.class.getClassLoader());
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("Before....");
return method.invoke(target,objects);
}
}
}
This is the error
Exception in thread "main" java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
at org.springframework.cglib.proxy.Enhancer.emitConstructors(Enhancer.java:1033)
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:724)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:358)
at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:582)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:110)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:108)
at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61)
at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:134)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:319)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:569)
at org.springframework.cglib.proxy.Enhancer.create(Enhancer.java:384)
at com.shao.demo.DemoApplication$MyMethodInterceptor.getProxyInstance(DemoApplication.java:53)
at com.shao.demo.DemoApplication.<init>(DemoApplication.java:25)
at com.shao.demo.DemoApplication.main(DemoApplication.java:14)
But when I declare the Person class in a new class file named Person.java there will be a correct output
Before....
I am saying