简体   繁体   中英

Getting a class's initializers using Javassist

Using Javassist, I am creating 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 use a "isEmpty" check on a class initializer, and if it is not empty, I have attempted the following two approaches. Both give me a no such constructor error:

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 B = 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.

Solved (kind of):

I was confusing constructors and initializers. It works to use a try/catch block and whenever it enters a catch block, it assumes a non-empty class constructor, in which case it inserts an empty constructor:

    try{
    //stuff 

}catch(Exception e){
            //cc is the ctclass object
    CtConstructor blank = new CtConstructor(null, cc); 
    cc.addConstructor(blank);
}

I am still hoping to figure out how to collect the expected parameters instead of injecting empty constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM