Hi
Unfortunately, you have to override some methods of BCEL's class loader to get actually class instrumentation/generation on the fly. Even so, because of the JLS (or JVM spec, I am not sure right now), you can not have different byte code for classes with same name loaded with the same class loader. I am affraid, beacuse of this you can never execute:


GenerateurVapeur newInstance = (GenerateurVapeur)newClass.newInstance();

in your code without ClassCastException (newClass' instances will be thought as different, unassignable to GenerateurVapeur; GenerateurVapeur already loaded by your context classloader several lines above). I must confess, I have never tried this, so if you have success, pls, inform me.

What I am doing when have to do what you want:
1. Obtain JavaClass from a repository without using any Class-es, just String names.
2. Mess with the class, and make it implement a useful interface.
3. Dump the class into a fake classloader or even on the disk.
4. Load the class and typecast to the useful interface
5. enjoy



[EMAIL PROTECTED] wrote:


How to obtain a new instance of a class which was modified by BCEL?

When I execute this code, a exception "java.lang.NoSuchFieldError" appears.

The goal of this code is to remove the field "libelle".

Have you an idea ?

thanks.


ClassGen clazz =new ClassGen(Repository.lookupClass(GenerateurVapeur.class));


   // Get the field "libelle".
   Field prpReelle =  clazz.containsField("libelle");

   // Remove the field. 
   if(prpReelle!=null)
        clazz.removeField(prpReelle);
                
   JavaClass classeJava = clazz.getJavaClass();

try{

     // Save the class
     dumpClass(classeJava,GenerateurVapeur.class);

     org.apache.bcel.util.ClassLoader cl = new
org.apache.bcel.util.ClassLoader(ClassLoader.getSystemClassLoader());

Class newClass = cl.loadClass(GenerateurVapeur.class.getName());
// Try to get a new instance of "GenerateurVapeur"
GenerateurVapeur newInstance = (GenerateurVapeur)newClass.newInstance();


   }catch(Exception exp){
     exp.printStackTrace();
   }


---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]





--------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to