Tuesday, October 2, 2012

Common mistake with Date



Use ‘dd/MM/yyyy’ instead of ‘dd/mm/yyyy’ when you are working with SimpleDateFormat to format. otherwise 'mm' will be considered as mints.

Can we access private methods in other class?..yes we can using reflection api


Yes...We can access private methods in other class using reflection API

Example code:

MyClass.java with private method
public class MyClass {

private String myPrivateMethod(String name) {
//Do something private
return "Hello "+;
}
}

Test class:  MainTest.java public class MainTest class{

private MyClass underTest;


public static void main(String []args)throws Exception {

MyClass underTest= new MyClass();

Class[] parameterTypes = new Class[1];
parameterTypes[0] = java.lang.String.class;

Method m = underTest.getClass().getDeclaredMethod("myPrivateMethod", parameterTypes);
m.setAccessible(true);

Object[] parameters = new Object[1];
parameters[0] = "Shekhar Reddy!";

String result = (String) m.invoke(underTest, parameters);
System.out.println(result )//Shekhar Reddy!

}


}
outPut: Hello Shekhar Reddy!

JUnit test case using Mock API

Mock API helps to create dummy object and returns back something to program when we are calling any method on that dummy object instead calling actual object.
Ex:
context.checking(new Expectations() {{
      oneOf (accountDAO).selectAccount(with("1234")); 
      will(returnValue(null));
  }});
 
 
Here we are asking Mock api return "null" value when I Call  
selectAccount method with 1234 value on AccountDAO object.

You can find very good example with maven integration in the below link.

http://onjavahell.blogspot.in/2009/05/good-unit-testing-with-jmock.html

Singleton object using Enum type

Since Java 1.5, there is a new approach to implement Singletons. Simply make it an enum type :
public enum MySingleton {

  INSTANCE;

  //Singleton method
  public void someMethod( ) {...}
}
Accessing the enum singleton :
MySingleton.INSTANCE.someMethod( );

New in spring 2.5 and Dependencies injection with Spring annotations (@Repository, @Service, @Autowired)

Click on below link to know what is new in spring 2.5

http://www.infoq.com/articles/spring-2.5-part-1
 Click below link to find simple example code with old and new bean configuration Dependencies injection with Spring annotations (@Repository, @Service, @Autowired). 
http://onjavahell.blogspot.in/2009/04/dependencies-injection-with-spring.html