سؤال

Hello dear members of SOF!

What I am looking for? I've been searching and searching around web how can I implement/inject interface on class(that has been compiled of course) and add the required methods by the interfaces on the class. I've also been trying to learn BCEL and ASM as much as I can but I am low in resources (even with my dear friend Google) so I am hoping I can find help here! I am not expecting you to spoon feed me or anything but I need some directions! :) I know theres that great book in ASM site and quite alot tutorials about everything about them but I just can't figure it out how could i possibly add interface/methods of it as I stated before. What have I tried? I found this link here but it didn't work out as I expected.. I know exactly what I want to do but I don't know how can i achieve it.. heres example!

public class Cat {
 public int age;
}

public interface Animal {
 public int getAge();
}

heres implementation of that method:

public int getAge(){
 return age;
}

so dear SOF members, how would this work out?

هل كانت مفيدة؟

المحلول

I've had some experience with BCEL, what you want is to start with a custom class loader that detects what classes you want to redefine; for each such class get the BCEL JavaClass object (use f.e. the ClassLoaderRepository), then modify that class to your liking. When you're done, get the classfile from the JavaClass and use ClassLoader#defineClass to pass it to the JVM for definition.

Now, to implement the actual methods, I would suggest to write a test class containing your code, then run BCELifier on the resulting class file, which will print out the Java BCEL source code required to generate that class file. Inspect it and copy-paste to your liking.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top