which object method of interface implementation will be called - java

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.

Related

What exception to use to prevent a method from being called multiple times?

I have a method that should only be called once during an object's lifetime. In order to ensure that this is the case, the method sets a boolean flag in the Object to true so it can later check if this method has already run. I am currently throwing an IllegalArgumentException (with a descriptive message) if this method is called a second time during a single object's lifetime, but that doesn't feel quite right to me, since the problem is not actually with the arguments themselves. Is there a better exception to use than an IllegalArgumentException?
I chose not to use an assert statement in this case, because the class and method are both visible outside the package, so the problem may be caused by code outside of my package. Is that correct thinking?
Throw an IllegalStateException.
But since exceptions shouldn't be part of the ordinary control flow, you should add a companion method, which returns a boolean that indicates whether the next call to the method will be successful.
An example for such a companion method is Iterator#hasNext().
A well-designed API must not force its clients to use exceptions for
ordinary control flow. A class with a “state-dependent” method that
can be invoked only under certain unpredictable conditions should
generally have a separate “state-testing” method indicating whether it
is appropriate to invoke the state-dependent method. For example, the
Iterator interface has the state-dependent method next and the
corresponding state-testing method hasNext.1
1: from Effective Java, Chapter 9: Exceptions
What should worry you more than the specific exception type is the fact that you created a bad design here.
Good interfaces make it easy to do the right thing and hard to do the wrong thing.
Meaning: your current implementation makes it easy to call that method twice; respectively you now force your clients to always check if that method was already called.
So, instead of spending your time on the exception type: step back and figure how to dissect your one class into two classes for example. And find a nice so that calling that specific method gives you a different object to work on. Or check if you should rather use a state machine to solve this problem.

Overriding a methods internal behavior

There is a class A that implements a method doBlah. I have a class B that subclasses A and has an #Override method doBlah. After I perform some simple manipulation in B.doBlah, I call A.doBlah.
A.doBlah calls a static method C.aStaticMethod.
A and C are part of an external library I can't modify.
Id like to have a static method CC.aStaticMethod called by A.doBlah in place of C.aStaticMethod. Would this be possible using any design patterns/hacks?
[EDIT]
I do have the source to A and I can include files from them into my code and modify etc if required. However, I cant modify the A package as such.
If you can't modify A or C, and call A directly, the answer is no.
If, on the other hand, you don't need to call A.doBlah directly, you can override it's behavior (provided the method is not final), in your own class, and have it call CC.aStaticMethod.
If you do have access to the source, you can do a very, very ugly hack:
Create a class A in exactly the same package as the original, and modify the method doBlah to call what you need.
Keep in mind that this has quite a few drawbacks, namely, if A belongs to an external library, you have NO way of knowing if an update to that library will break your code or not, since you'll be running an older version of A.
This is basically to say that this approach can turn quickly into a maintenance nightmare.

JNI: How to get method signature for debugging purposes

Can I enumerate all native methods in java, those that have to be
implemented in c/c++ using JNI?
Can I enumerate native methods by
name (there could be multiple overloads with the same name)?
How can I retrieve method signature to be able to generate the method
signature used by JNI?
Is there a way to check if all native jni methods have been bound properly, instead of trying to call them and get java.lang.UnsatisfiedLinkError exceptions. Sometimes method signature changes on either side without properly updating java or c++ side and I'd like to add some debugging code to detect these issues and handle them (perhaps by generating proper method signature and printing it to the log so I can easily fix the code).
I prefer JNI solution, but if something can be done with help on java side then it's ok also.
If I use registerNatives and register methods that weren't declared in java then it fails and prints it to logcat:
E/dalvikvm( 1445): ERROR: couldn't find native method
E/dalvikvm( 1445): Requested: Lcom/bla/bla/bla/Test;.nativeTestXX:()Z
but I'd like to catch this error and handle it myself. Is it possible to do it?
EDIT:
In my JNI code I have a static nativeInit (as suggested in Android JNI tips) that registers all native methods. In that same function I'd like to verify that all native methods are properly bound. That is, I don't need to wait till some uninitialized method is called and the app exists. The problem that I have: there is a lot of jni code written at different times by different ppl and some methods simply became incorrect, but they are used only in some obscure conditions. The best way for me, I think, is to check that all native methods are bound to some c++ function. The other problem, is that part of JNI code uses binding by exporting all these Long_java_names where method signature changes on either side cannot be detected.
There is no call to check for "unbound" native methods. Using RegisterNatives to perform explicit registration ensures that all methods you register have a matching declaration in the Java sources, but there is no way to check for native-declared methods for which there is no implementation (other than calling it and catching the exception).
At the point where a method with a native implementation is called, if nothing has yet been registered then Dalvik will search through the various shared libraries to find a match. What it sounds like you want is a way to force this search and check the result without actually calling the method. There is no such thing.
There are various ways to generate lists of native-declared methods, either statically or at runtime, but you also need a way to determine if an implementation is available. You're better off in the long run having unit tests that exercise the code.

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.

Reflecting method's actions in 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.

Categories

Resources