开发者

Using methods in one class (classsA) in which another class (classB) is loaded using reflection api java

I have a requirement as follows. I have loaded a set of classes [present in a jar file] using Reflection in java. Now in the loaded class, I want to call certain methods in the loading class.

For example, assume class A and class B are there. Using reflection I am loading class 开发者_如何学CB from class A. Therefore I am able to use the methods in class B from class A. But I want to use some methods in class A from class B.

Your help is greatly appreciated.

Thanks..


It seems like a faulty design. Try to rethink it. Your current setup may be solved by applying a singleton pattern. For example:

abstract class SomeSingleton {

    private static SomeSingleton instance;

    public static void setInstance(SomeSingleton instance) {
        this.instance = instance;
    }

    public static SomeSingleton getInstance() {
        return instance;
    }

    public abstract void someMethod();
}

class ClassA extends SomeSingleton {

    public ClassA() {
        SomeSingleton.setInstance(this);
    }

    @Override
    public void someMethod() {
        System.out.println("some methid is called");
    }
}

class ClassB {

    public void aMethod() {
        SomeSingleton.getInstance().someMethod();
    }
}

This way ClassB does not have to know about ClassA. It only knows about a service. ClassA reports to SomeSingleton that it can provide the service. - So everyone is happy.


You could insist that your class B (the loaded class) has a constructor which takes A as a parameter:

class B {
    public B(A a) {
        // etc...
    }
}

And then in your reflection code, instantiate the class with that constructor. B can now do whatever it needs with A. You can create a new instance for a specific constructor like this:

Class<B> clazz = B.class;
clazz.getConstructor(new Class[] {A.class}).newInstance(a);


You could let classB implement a method through which you provide an instance of classA and then use this instance from inside classB.


You can ONLY do this by explicitly telling your instance of classB about classA, e.g. by calling

b.setA(this)

from a.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜