简体   繁体   中英

How to implement object proxy or Class proxy in Java?

I have requirement to extend a .class file in my project and need to override a simple method. Consider i have class A which is in some .jar package.Now i want to override test() method of class AI did it using creating subclass B of A and override it. Now in my application package (it is .jar) Object is created for class A. This object invoke the method of class A. But i want to make a call to class B method.

My idea is to proxy the object creation in whole application. Whenever the obj of class A is created at that time i want to some configuration to create object of class B & handed over to class A initiate.

Some one please help me to implement this type of mechanism.

You can block or control class instantiation only if the constructor is private .

If you can't overwrite the original base class and you want to proxy it, you need a factory and advise programmers to use the factory instead of calling directly the constructor of the base class.

In the factory code you can return a subclass that operates as a proxy of your base class.

Remember that this is only an advice. You can't block programmers to manually create instances of a class with a public constructor.

Following is the simple approach(using type casting) through which we can use Parent class object to call Child class method :

package testA;

public class A 
{

    public static void main(String[] args) 
    {
        System.out.println("Hello World!");
    }

    public String aMethod(){
        System.out.println("Calling aMethod");
        return "aMethod";
    }
}



package testB;
import testA.*;

public class B extends A
{

    public static void main(String[] args) 
    {
        System.out.println("Hello World!");
        A aClass = new B();
        aClass.aMethod();
        ((B)aClass).bMethod();
    }

    public String bMethod(){
        System.out.println("calling B method");
        return "bMethod";
    }
}

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