Tip: Null casting

When having overloaded methods in one class and calling one of these methods to pass the null value as a parameter. This causes ambiguity to the compiler to decide which method to use. So you can cast the null to the specific type for the method you want to call. Bellow is a snippet to make things clear.
 * @author Belal
public class MyClass {

    public void setObject(String s) {
        System.out.println("In setObject(String s)");

    public void setObject(Long l) {
        System.out.println("In setObject(Long l)");

    public static void main(String[] args) {
        (new MyClass()).setObject("test");
        (new MyClass()).setObject(new Long(0L));
        (new MyClass()).setObject((String) null);
        (new MyClass()).setObject((Long) null);
The output should be similar to this:
In setObject(String s)
In setObject(Long l)
In setObject(String s)
In setObject(Long l)


Popular posts from this blog

JavaOne 2015 Session: EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples by Gohar

Spring Core - Different Types of Bean Injection

PrimeFaces Push with Atmosphere