Friday, June 26, 2009

Can you override Static Methods in Java?

Question: Can you override Static Methods in Java?


Answer: Well... the answer is NO if you think from the perspective of how an overriden method should behave in Java. But, you don't get any compiler error if you try to override a static method. That means, if you try to override, Java doesn't stop you doing that; but you certainly don't get the same effect as you get for non-static methods. Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods). Okay... any guesses for the reason why do they behave strangely? Because they are class methods and hence access to them is always resolved during compile time only using the compile time type information. Accessing them using object references is just an extra liberty given by the designers of Java and we should certainly not think of stopping that practice only when they restrict it :-)


Example: let's try to see what happens if we try overriding a static method:-


class SuperClass{

......

public static void staticMethod(){

System.out.println("SuperClass: inside staticMethod");

}

......

}


public class SubClass extends SuperClass{

......

//overriding the static method

public static void staticMethod(){

System.out.println("SubClass: inside staticMethod");

}


......

public static void main(String []args){

......

SuperClass superClassWithSuperCons = new SuperClass();

SuperClass superClassWithSubCons = new SubClass();

SubClass subClassWithSubCons = new SubClass();


superClassWithSuperCons.staticMethod();

superClassWithSubCons.staticMethod();

subClassWithSubCons.staticMethod();

...

}


}


Output:-


SuperClass: inside staticMethod

SuperClass: inside staticMethod

SubClass: inside staticMethod


Notice the second line of the output. Had the staticMethod been overriden this line should have been identical to the third line as we're invoking the 'staticMethod()' on an object of Runtime Type as 'SubClass' and not as 'SuperClass'. This confirms that the static methods are always resolved using their compile time type information only.

Difference between Dynamic Binding & Static Binding in Java

Difference between Dynamic Binding & Static Binding in Java

Dynamic Binding or Late Binding

Dynamic Binding refers to the case where compiler is not able to resolve the call and the binding is done at runtime only. Let's try to understand this. Suppose we have a class named 'SuperClass' and another class named 'SubClass' extends it. Now a 'SuperClass' reference can be assigned to an object of the type 'SubClass' as well. If we have a method (say 'someMethod()') in the 'SuperClass' which we override in the 'SubClass' then a call of that method on a 'SuperClass' reference can only be resolved at runtime as the compiler can't be sure of what type of object this reference would be pointing to at runtime.

...
SuperClass superClass1 = new SuperClass();
SuperClass superClass2 = new SubClass();
...

superClass1.someMethod(); // SuperClass version is called
superClass2.someMethod(); // SubClass version is called
....

Here, we see that even though both the object references superClass1 and superClass2 are of type 'SuperClass' only, but at run time they refer to the objects of types 'SuperClass' and 'SubClass' respectively.

Hence, at compile time the compiler can't be sure if the call to the method 'someMethod()' on these references actually refer to which version of the method - the super class version or the sub class version.

Thus, we see that dynamic binding in Java simply binds the method calls (inherited methods only as they can be overriden in a sub class and hence compiler may not be sure of which version of the method to call) based on the actual object type and not on the declared type of the object reference.

Static Binding or Early Binding

If the compiler can resolve the binding at the compile time only then such a binding is called Static Binding or Early Binding. All the instance method calls are always resolved at runtime, but all the static method calls are resolved at compile time itself and hence we have static binding for static method calls. Because static methods are class methods and hence they can be accessed using the class name itself (in fact they are encourgaed to be used using their corresponding class names only and not by using the object references) and therefore access to them is required to be resolved during compile time only using the compile time type information. That's the reason why static methods can not actually be overriden. Read more - Can you override static methods in Java?

Similarly, access to all the member variables in Java follows static binding as Java doesn't support (in fact, it discourages) polymorphic behavior of member variables. For example:-

class SuperClass{
...
public String someVariable = "Some Variable in SuperClass";
...
}

class SubClass extends SuperClass{
...
public String someVariable = "Some Variable in SubClass";
...
}
...
...

SuperClass superClass1 = new SuperClass();
SuperClass superClass2 = new SubClass();

System.out.println(superClass1.someVariable);
System.out.println(superClass2.someVariable);
...

Output:-
Some Variable in SuperClass
Some Variable in SuperClass

We can observe that in both the cases, the member variable is resolved based on the declared type of the object reference only, which the compiler is capable of finding as early as at the compile time only and hence a static binding in this case. Another example of static binding is that of 'private' methods as they are never inherited and the compile can resolve calls to any private method at compile time only.

Wednesday, June 24, 2009

Simple Junit Example:

Simple Junit Example:

Example 1:

//load spring bean configure file

@ContextConfiguration(inheritLocations=true, locations={ "classpath:bhg-services.xml" })

public class ValueMealsTest extends AbstractBaseSpringTest{

@Resource

private IRecipeDao recipeDao;

@Ignore

@Test

@Transactional

public void testGetStores(){

// here code to invoke the service

assertNotNull(storePromotionCounts);

assertTrue(storePromotionCounts.size()==1);

assertTrue(storePromotionCounts.get(0).getPromotionCount()==2);

}

}// class

Example 2:

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:foodlabContext.xml","classpath:service.xml","classpath:business.xml"})

class AbstractBaseSpringTest{

@Before

public void setupRequestResponse() {

// code to run before the test case start execute

}

public void testMethodName(){

//code to test the service

}

@After

public void setupRequestResponse() {

// code to run after the all test case execution completed

}

}// class

Tuesday, June 23, 2009

Eclipse Tip: Static Imports

One of the great features of Java 1.5 is Static Imports. In order to configure Eclipse to search for static imports in a particular class, you have to perform the following steps:

  1. Navigate to Preferences by clicking on the Window -> Preferences Menu Item
  2. Navigate to Java -> Editor -> Content Assist -> Favorites using the menu tree (or search for Favorites using the search bar at the top)
  3. Click the New Type button
  4. Type in the name of the Class that has static methods that you would like to be used when using Eclipse's Content Assist / Code Completion (eg Assert)
  5. Click on the Browse button which will bring up the Open Type Dialog using what you entered previously as the search criteria
  6. Find the class that you would like to add, and then click Okay on the Open Type Dialog
  7. Then Click Okay on the New Type Favorite Dialog.
Now when you are editing Java code, instead of typing Assert.assertEquals, you only need to type assertEquals, with Ctrl-Space, and the Assert Type will be searched for in order to resolve the static import.

Monday, June 22, 2009

Spring Aop with AcpectJ configuration.

Spring Aop with Aspectj Configurations:
 
The @AspectJ support is enabled by including the following
element inside your spring configuration:
  

Sharing common pointcut definitions :

package com.xyz.someapp;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
 
@Aspect
public class SystemArchitecture {
 
@Pointcut("execution(* com.xyz.someapp.dao.*.*(..))")
  public void dataAccessOperation() {}
 
  @Pointcut("execution(* com.xyz.someapp.service.*.*(..))")
  public void businessService() {}
}

Before advice

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
 
@Aspect
public class BeforeExample {
 
  @Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
  public void doAccessCheck() {
    // ...
  }
}
If using an in-place pointcut expression we could rewrite the above example as:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
 
@Aspect
public class BeforeExample {
 
  @Before("execution(* com.xyz.myapp.dao.*.*(..))")
  public void doAccessCheck() {
    // ...
  }
}

After returning advice

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
 
@Aspect
public class AfterReturningExample {
 
@AfterReturning("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
  public void doAccessCheck() {
    // ...
  }
}
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
 
@Aspect
public class AfterReturningExample {
 
  @AfterReturning(
    pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()",
    returning="retVal")
  public void doAccessCheck(Object retVal) {
    // ...
  }
}

After throwing advice

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
 
@Aspect
public class AfterThrowingExample {
 
@AfterThrowing("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
  public void doRecoveryActions() {
    // ...
  }
}
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
 
@Aspect
public class AfterThrowingExample {
 
  @AfterThrowing(
    pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()",
    throwing="ex")
  public void doRecoveryActions(DataAccessException ex) {
    // ...
  }
}

After (finally) advice

After (finally) advice runs however a matched method execution exits. It is declared using the @After annotation. After advice must be prepared to handle both normal and exception return conditions. It is typically used for releasing resources, etc.
 
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
 
@Aspect
public class AfterFinallyExample {
 
  @After("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
  public void doReleaseLock() {
    // ...
  }
}

Around advice

The value returned by the around advice will be the return value seen by the caller of the method. A simple caching aspect for example could return a value from a cache if it has one, and invoke proceed() if it does not. Note that proceed may be invoked once, many times, or not at all within the body of the around advice, all of these are quite legal.
 
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
 
@Aspect
public class AroundExample {
 
  @Around("com.xyz.myapp.SystemArchitecture.businessService()")
  public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
    // start stopwatch
    Object retVal = pjp.proceed();
    // stop stopwatch
    return retVal;
  }
}
 

Lucene Search configurations

================================================

pojo configuration:
=================
1. The first thing to do is to place an @Indexed annotation on the entity that will be
searchable through Hibernate Search

2.The second (and last) mandatory thing to do is to add a @DocumentId on the
entity’s identity property. Hibernate Search uses this property to make the link
between a database entry and an index entry

package com.manning.hsia.dvdstore.model;

@Indexed
public class Item {

@DocumentId
private Integer id;

@Field
private String title;

@Field
private String description;

@Field(index=Index.UN_TOKENIZED, store=Store.YES)
private String ean;

private String imageURL;
//public getters and setters
}



=================================================================

While building a query seems like a lot of steps, it’s a very easy process. In summary:

1 Build the Lucene query (using one of the query parsers or programmatically).

String searchQuery = "title:Batman OR description:Batman";

QueryParser parser = new QueryParser("title",new StandardAnalyzer());

org.apache.lucene.search.Query luceneQuery;

try {
luceneQuery = parser.parse(searchQuery);
}
catch (ParseException e) {
throw new RuntimeException("Unable to parse query: " + searchQuery, e);
}

An analyzer is responsible for breaking sentences into individual words.

2 Wrap the Lucene query inside a Hibernate Search query.

FullTextSession ftSession = org.hibernate.search.Search.getFullTextSession(session);


org.hibernate.Query query = ftSession.createFullTextQuery(luceneQuery,Item.class);


3 Optionally set some query properties (such as pagination).

query.setFirstResult(20)
.setMaxResults(20);

4 Execute the query

List results = query.list();
for (Item item : (List) results) {

display( "title: " + item.getTitle() + "\nDescription: " +item.getDescription() );
}