Reflecting method's actions in Java - java

I'd like to know how to - if even possible - reflect what method calls are executed inside the method during execution. I'm especially interested in either external method calls (that is, methods in other classes) or calling some specific method like getDatabaseConnection().
My intention would be to monitor predefined objects' actions inside methods and execute additional code if some specific conditions are met like some method is called with specific values. The monitor would be completely external class or a set of classes with no direct access to the object to be monitored by no other way than reflection.

Aspect J will solve your problem.
Try to define a pointcut like this:
pointcut profilling(): execution(public * *(..)) && (
within(com.myPackage..*) ||
In this way you will catch all the call to any public method within the package com.myPackage. Add as many within clauses you need.
Then add the following code:
Object around(): profilling() {
//Do wherever you need before method call
proceed();
//Do wherever you need after method call
}
IF you want to learn something more about aspectJ follow this guide.

I'd expect BCEL to be able to do this. From the web site:
The Byte Code Engineering Library is
intended to give users a convenient
possibility to analyze, create, and
manipulate (binary) Java class files
(those ending with .class).
The "analyze" part being the important bit here. The JavaDoc isn't visible on the web site (as far as I can see) so I can't easily be sure whether or not it'll help you, but it's a reasonable starting point.

BCEL should offer this capability, but ...
... your requirements sound a lot like Aspect-Oriented Programming (AOP), so you should probably also look at AspectJ (with Eclipse tooling).
The main advantage of AspectJ is that it offers a well-designed way to express your specific conditions.

Related

how to create a custom stacktrace in java with additional info (like parameters)?

I was assigned a task to create a custom stacktrace like output to a log file for some specified functions, but instead of just using the class and method names I would also have to output the parameters and their values.
This is supposed to be a separate jar that could run on any java project, after.
I don't even know if such thing is possible, let alone where to start.
Any help would be appreciated.
EDIT: there is other library that does that by using native VM api: https://github.com/cretz/stackparam it also modifies Throwable class to always print that modified stacktrace.
The only possible way I can think of is using agents and instrumentalization, but agent needs to be added to startup command line.
Then I would register transformer to transform every class (remember that some basic java classes might be already loaded) using ASM library and add code to beginning of every method invocation to manually track each method class and pass it to my library that would track them:
// note that parameters names might not exist in runtime if code was compiled without a flag to include them.
public void doSomething(String name, int something) {
MyLib.enterMethod(ThisClass.class, new MethodSignature(void.class, String.class, int.class), new Argument("name", name), new Argument("something", something));
try {
// original code
} finally { // so we don't need to care about return in the middle of original code or exceptions
MyLib.exitMethod();
}
}
enterMethod would add invocation frame to some queue and exitMethod would remove last added frame. Note that you should have separate queue for each thread, use some Map<Thread, MyFrame> or ThreadLocal it might be good idea to use some weak references for threads.
And then you could use frames from that queue to create own stacktrace.
But doing something like that might decrease performance a lot - not even just because cost of this code, but adding that to every setter/getter might cause that methods to never be inlined and affect performance even more.
So it is possible but I really don't recommend doing something like that.
Also some other transformers added by other libraries might affect results, it might be good idea to also compare your stacktrace with original stacktrace to find any missing methods that you didn't transform - like native ones, and add them to your stacktrace but without that additional data.
If you really need to support native methods too - then you can create more advanced transformer that would add enterMethod/exitMethod before and after call to native method.
Also if this is only for debugging you could use debugging API so it would only work as a debugger.

which object method of interface implementation will be called

I have a code like below in project. Here by casting with interface we are calling the method authenticate() of the service IAuthenticateService. Now there are 5 subclasses which have the same method implementation and Implementing the same interface IAuthenticateService. By seeing the code how will I come to know which class method implementation has been called? I'm little bit confused of interface design.
((IAuthenticateService) AuthServiceApp.getInstance().getContext()
.getService(ServiceEnum.CredentialService.name()))
.authenticate(inputParams);
You can't know just by reading this code.
But, the program will know at runtime which implementation to call : the object returned by AuthServiceApp.getInstance().getContext() will have a type, which one will have a single implementation of the method getService, and this implementation will be called.
As a programmer, you don't need to know more. The programming by contract paradigm allows you not to bother about which implementation will be called. All you need to know is that given a certain environment, you will get an instance of a context on which you can call getService(), AND it will provide you with a service.
The rest is details, you don't have to worry about it.
Of course, when you are debugging, that's a different story : you want to know which implementation is executed as it might be buggy. In that case, just follow the debugger to see which code is really executed, but otherwise, you should not care, that's all what polymorphism is about : gaining abstraction.
Well you not being able to tell what implementation of IAuthentication is being returned is the whole point of interfaces. We use interfaces to segment parts of code away from each other. This makes programs more extensible and versatile which drives code reuse. It is a very powerful concept and the corner stone of modern software development. The client (the code using the interface's methods) does not care what is on the other side of the interface (ie the implementer of the interface). This allows for the client side to change at runtime. The fact that you don't know is what gives its power. In order to understand this concept you have to think about how the compiler works and what it does when it compiles code.
In compiled languages the compiler translates source code into machine instructions. When it is translating a method into a machine code the method receives an address in memory where the method starts. When another piece of code calls that method that memory address is written in the code on the client code. That memory address is fixed so that piece of code can't call any other method at runtime. It will always call that one method and never a different method.
For example say we have something like this:
private int someMethod() { ... }
The compiler says someMethod is located at 003. So when it's compiling code like this:
public myMethod() {
this.someMethod();
}
It says myMethod calls someMethod, and looks up where in memory someMethod lives. Roughly it will write out something like:
// myMethod
call 003
Now that method invocation (aka call site) can only ever call someMethod forever. It will never call any other method but that exact method.
But in OO languages we can vary which actual method is called at runtime. That means the compiler can't write that memory address into the callers code when it is compiling the class. Instead it has to look up that method address at runtime. How it does that is by looking up the method by name in the object it is passed at runtime. So the compiler might do something like this:
// myMethod
methodAddress = this.methodsAddresses['someMethod']
call methodAddress
It's that lookup (sometimes called the virtual pointer table) that enables methods to change depending on what someObject points to, and that lookup allows it to vary at runtime.
This is all well and good until you need to debug something. If you are trying to debug something its easiest if you use a debugger, and drop a break point in your client code and you can easily look at that an many other things along with stepping into the code. You can also print someObject.getClass().getName() to find the name, but that is just the beginning if you are debugging.

Instrumenting a Java anonymous inner class object

So, given the following code:
public MyInterface getMyInterface() {
return new MyInterface() {
public SomethingElse getSomethingElse() {
// ....
}
}
}
...
MyInterface obj = getMyInterface();
Is there some way to instrument a call to getSomethingElse() on that obj? To go in and do some bytecode modification or something?
I have production code in there that in a different situation (call it "design time") I want to add some tracing/logging and such code for help in troubleshooting and analysis. Performance is critical for the production case so I want to leave it without the extra tracing/logging overhead. But in the design time situation, I want to have all the trace info.
Yes, it is possible to do what you're asking, although there are definitely better ways to accomplish it - the most obvious would be to create a default implementation of MyInterface, and then a "tracing" subclass of it that extends and logs before invoking the superclass version.
If instrumentation is your only option, then when running at design time, you can start your project with a java agent in Java 5 or add a java agent to the classpath at runtime in Java 6. See the instrumentation documentation.
To instrument the class, you will probably want to use a tool like ASM. The steps would be something like this:
In your Agent class, implement java.lang.instrument.ClassFileTransformer .
In your agentmain() or premain() method, request to transform classes.
When you receive a call to the transform method, you can check if the class implements MyInterface by using Class.getInterfaces().
Optionally, you can check to see if its Class.getEnclosingClass() is the class in which you wrote/found this code.
If the Class passes these sanity checks, then create a ClassWriter that adds logging to the getSomethingElse() method. The ASMifier helps a lot when trying to figure out how to generate the code you want.
Then, in production, none of that code will exist. In development, you would add your Java Agent in your environment, which would enable your debugging.
Again, there are almost certainly better ways to do this, but there are good reasons to use instrumentation, and this is a mini-crash course in doing it.
Hope that helps,
If you want to turn on logging on in development, the simplest thing to do is
if(LOGGER.isDebugEnabled())
LOGGER.debug("my debug message");
The over head added is sub-nanosecond so even if you are working on a system where every nano-seconds count, this is still the best pattern to use.
You can get the class with
Class.forName("package.OuterClass$NNN");
You need to call a constructor which takes an instance of the outer class.
This sounds like a good case for using aspects.
You can simply apply logging/tracing code around any methods you want in your testing environment and leave them out when you move to production.

AspectJ pointcut on method variable, is it possible?

I have been using AspectJ for a while and it works great on object scope fields containing annotations. I just ran into a situation where I want to annotate a variable of method scope that will work with my pointcut but I am having trouble with it.
Here is the pointcut that I am using. It works fine if my variable is a field for the object, but if I reduce the scope to a method (variable declared inside the method), then it doesn't work anymore and I am not sure why. Let me know what I can do, thanks.
after(final Trigger trigger): set(#Triggereable * *) && args(trigger)
{
System.out.println("trigger flush");
}
Also, here is an exmaple of what I want to work. That System.out.println above should fire when the Trigger is instantiated:
public void foo()
{
#Triggereable
private Trigger trigger = new Trigger();
}
If you came to such situation, you probably trying to change implementation instead of applying actual cross cutting concerns. Basically, it is not what AOP and AspectJ is supposed to be used for.
As a work around, you can either extract relevant functionality into a separate method and then apply your aspects to that method or alternatively, you can replace an entire method with that local variable, using around advice.
More over, in your particular example, the pointcut can be applied to the constructor execution within scope of a given method, so you can do practically the same thing without binding to a local variable.
AspectJ does not currently support pointcuts on local variables (read the FAQ entry).
I seem to recall a recent discussion about such a feature possibly added soon, but I could not find it in the AspectJ issue tracker nor in the Mailing List archives

In Java, how can I construct a "proxy wrapper" around an object which invokes a method upon changing a property?

I'm looking for something similar to the Proxy pattern or the Dynamic Proxy Classes, only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like the Proxy class in Action Script 3 would be fine.
Here's what I want to achieve in general:
I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk.
The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off.
During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value.
Edit: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method.
If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by manipulations on the byte code level though.
Actually, the easiest way to do it is probably by using AspectJ and defining a set() pointcut (which will intercept the field access on the byte code level).
The design pattern you are looking for is: Differential Execution. I do believe.
How does differential execution work?
Is a question I answered that deals with this.
However, may I suggest that you use a callback instead? You will have to read about this, but the general idea is that you can implement interfaces (often called listeners) that active upon "something interesting" happening. Such as having a data structure be changed.
Obligitory links:
Wiki Differential execution
Wiki Callback
Alright, here is the answer as I see it. Differential Execution is O(N) time. This is really reasonable, but if that doesn't work for ya Callbacks will. Callbacks basically work by passing a method by parameter to your class that is changing the array. This method will take the value changed and the location of the item, pass it back by parameter to the "storage class" and change the value approipriately. So, yes, you have to back each change with a method call.
I realize now this is not what you want. What it appears that you want is a way that you can supply some kind of listener on each variable in an array that would be called when that item is changed. The listener would then change the corresponding array in your "backup" to refect this change.
Natively I can't think of a way to do this. You can, of course, create your own listeners and events, using an interface. This is basically the same idea as the callbacks, though nicer to look at.
Then there is reflection... Java has reflection, and I am positive you can write something using it to do this. However, reflection is notoriously slow. Not to mention a pain to code (in my opinion).
Hope that helps...
I don't want to intercept method calls before they are invoked on the real object, but
rather I'd like to intercept properties that are being changed
So in fact, the objects you want to monitor are no convenient beans but a resurgence of C structs. The only way that comes to my mind to do that is with the Field Access call in JVMTI.
I wanted to do the same thing myself. My solution was to use dynamic proxy wrappers using Javassist. I would generate a class that implements the same interface as the class of my target object, wrap my proxy class around original class, and delegate all method calls on proxy to the original, except setters which would also fire the PropertyChangeEvent.
Anyway I posted the full explanation and the code on my blog here:
http://clockwork-fig.blogspot.com/2010/11/javabean-property-change-listener-with.html

Categories

Resources