How to implement object proxy or Class proxy in Java?

470 Views Asked by At

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 A.I 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.

2

There are 2 best solutions below

1
Davide Lorenzo MARINO On

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.

0
Gagan Kumar On

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";
    }
}