JBoss Community

Re: Grabbing an existing class's constructors?

created by Melissa Dale in Javassist - View the full discussion

Thank you for replying, You are right, I do understand the difference between class initialization and object initialization in theory, and what I had posted was an extremely sloppy attempt made in desperation (although I acknowledge it is entirely possible I am failing to keep them separate in practice

 

Instead of using ".isEmpty()" I have used a try/catch, where it tries to create the coupling, and if it fails I assume it's because a ctclass's constructor is not empty. In the catch block I attempt to insert an empty class constructor on the ctclass object (so to overload the constructor) So it's like this:

 

String from_class = from.getName();

    //Persistent Coupling

    if(strength == 'P' || strength == 'p'){

             try{

                      String toBeAdded = from_class + varname+" = new " + from_class+"();";

                      CtField f = CtField.make(toBeAdded, to);

              to.addField(f);

             }

        //Hopefully this will catch cases where constructors are not empty and insert a dummy instructor

             catch(Exception e){

                      from.makeClassInitializer();

 

                      String toBeAdded = from_class + varname+" = new " + from_class+"();";

                      CtField f = CtField.make(toBeAdded, to);

                      to.addField(f);

             }

 

 

I still get a 'Exception in thread "main" javassist.CannotCompileException: [source error] no such constructor'. And as I mentioned, ideally I would like to use the getConstructors() on a ctclass to get the array of constructor objects, but this is much fuzzier in my mind. Once I have the array of constructor objects, is there a way to determine the object types? If I can loop through the array I can make a coupling with dummy variables, becasue I don't really care about the program's execution after it it coupled, only that it will compile. Something roughly like:

 

CtConstructor [] consts = new CtConstructor[];

 

 

ArrayList <?> results = new ArrayList<?>();

 

 

for (int i=0; i<consts.length(); i++){

          if (consts[i].type == int){

                    results[i]=13;

          else if (consts[i].type == double){

                    results[i] = 13.5;

          }

          else if (consts[i].type == char){

                    results[i] = 'M';

          }

          else if (consts[i].type == float){

                    results[i] = 13.5;

          }

          else if (consts[i].type == double){

                    results[i] = 13.5;

          }

          else if (consts[i].type == boolean){

                    results[i] = 13.5;

          }

          else{

                    results[i]=null;

          }

          }//for

}//method

Reply to this message by going to Community

Start a new discussion in Javassist at Community