Grabbing an existing class's constructors?
mdale May 20, 2013 4:19 PMI am a graduate student studying software engineering and technical debt. For my research I am using Javassist to create coupling between classes. However there is obviously a problem when I try to create an instance of a class that takes in parameters. I would really like to be able to grab a CtClass's initializers (if they're not an empty constructor), and then pass in the variables it is expecting. for example, consider I am trying to make an instance of class B in class A:
Public class B{
public int foo;
public char spam;
public B(int bar, char eggs){
foo = bar;
spam = eggs;
}
}
Public class A{
B injected = new B(X,X);
}
currently I attempt to use a "isEmpty" check if the class initializer if it is not empty, in which case I have attempted the following two approaches. Both give me a 'no such constructor' error:
if(from.getClassInitializer().isEmpty()){
String toBeAdded = from_class +" injected = 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
else{
}
I think the method "getClassInitializers" should return a CtClass's constructors as an array, but I'm unsure what to do with this array, which eclipse won't even let me declare. I'd like to loop through an array of expected parameters and make dummy variables of that type so I can do something like:
B injected = new B (13, w);
Worse case scenario, I could create a blank class initializer in B so I could do
injected B = new B();
I think I should be able to use the makeClassInitializer() method, but that does not work for me, as I still get a no such constructor error. Something like:
else{
from.makeClassInitializer();
String toBeAdded = from_class + "injected = new " + from_class+"();";
CtField f = CtField.make(toBeAdded, to);
to.addField(f);
}
I would really appreciate any help or input you may have to offer. Thanks!