Search code examples
javaprogramming-languages

is this possible in java or any other programming language


public abstract class Master
{
    public void printForAllMethodsInSubClass()
    {
        System.out.println ("Printing before subclass method executes");
            System.out.println ("Parameters for subclass method were: ....");
    }
}

public class Owner extends Master {
    public void printSomething () {
        System.out.println ("This printed from Owner");
    }

    public int returnSomeCals ()
    {
        return 5+5;
    }
}

Without messing with methods of subclass...is it possible to execute printForAllMethodsInSubClass() before the method of a subclass gets executed?

update:

Using AspectJ/Ruby/Python...etc Would it also be possible to print the parameters? Above code formatted below:

public abstract class Master
{
    public void printForAllMethodsInSubClass()
    {
        System.out.println ("Printing before subclass method executes");

    }
}

public class Owner extends Master {
    public void printSomething (String something) {
        System.out.println (something + " printed from Owner");
    }

    public int returnSomeCals (int x, int y)
    {
        return x+y;
    }
}

Solution

  • AspectJ can provide this functionality for you, but it's a separate compilation step and some extra libraries involved.

    public aspect ServerLogger {
        pointcut printSomething ();
    
        before(): printSomething()
        {
                (Master)(thisJoinPointStaticPart.getTarget()).printForAlMethodsInSubClass();
        }
    }
    

    The Eclipse Project provides a great implementation of AspectJ that integrates nicely with Eclipse and Maven. There's a boatload of great documentation available for it, and a lot of really good material for it here on StackOverflow.

    [update]

    To access parameter info, you can use the

    thisJoinPoint.getSignature(); 
    

    method to access information about the function being called if the returned Object is an instance of MethodSignature, you can use Signature.getParameterNames() to access the parameters to the function being called. You'd have to use a bit of reflection to actually get at the values, I think - AspectJ doesn't seem to handle this for you. I'd have to actually do some experimentation to get some working code for you.