Re: Instrument a class and get new instance of it

Simon Kitching <[email protected]> Fri, 14 Jul 2006 11:47:55 +1200
Newsgroups gmane.comp.jakarta.bcel.user
Message-ID <1152834476.5282.37.camel@blackbox>
Hi Zach,

You can turn an array of bytes into a Class using the method
ClassLoader.defineClass. This method is protected, but you can call it
by using reflection (locate the Method object for it, then call
Method.invoke). Yes it's rather ugly but it works.

And of course once you've got the Class, you can call Class.newInstance
or similar to create instances of that class.

Someone else will have to tell you how to create the modified bytecode.

Regards,

Simon


On Thu, 2006-07-13 at 18:30 -0400, Zach Cox wrote:
> I would like to be able to, at run-time, modify the bytecode of a method of
> an existing class and then get a new instance of that class that has the
> modified bytecode.  For example, here's a simple class:
> 
> public class MyClass
> {
>   public double getDouble()
>   {
>     return -1.0;
>   }
>   
>   public String toString()
>   {
>     return String.valueOf(getDouble());
>   }
> }
> 
> At run-time I'd like to change the value returned in the getDouble method
> and then get an instance of MyClass that returns the new value.  I also need
> to be able to do this multiple times with different return values.  For
> example, I'd create one instance of MyClass that returns 1.0, another
> instance that returns 2.0, etc.
> 
> I understand the examples that show how to create new ClassGen, MethodGen,
> InstructionList, etc and then write out a modified .class file,    but I
> want to avoid writing to the filesystem and do everything in memory.  Can
> anyone provide any pointers to the BCEL classes/methods  to create a new
> instance of a modified JavaClass?
> 
> Thanks,
> Zach
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [email protected]
> For additional commands, e-mail: [email protected]
>