Fork me on GitHub

Saturday, July 13, 2013

Writing method with dynamic return type without type casting

I have often come across this requirement across multiple projects, where we need to write a method, which can potentially return object of any class, and still you would not like to do a typecasting. Something like this:
MyClass myClass = getDynamicClass(MyClass.class);

Instead of :
MyClass myClass = (MyClass) getDynamicClass(MyClass.class);

Common example of such use case is where you would do some lookup of a dynamic service (as in OSGi) and return the object found. However, with Java 5 and above this is easy. So, if your earlier code was:
protected Object getDynamicClass(Class interfaceClass) {
    Object obj = null;
    // code to create / lookup the dynamic object
    return obj;
}
This code can be converted as follows:
protected <ReturnType> ReturnType getDynamicClass(Class<ReturnType> interfaceClass) {
    Object obj = null;
    // code to create / lookup the dynamic object
    if (interfaceClass.isInstance(obj)) {
        return interfaceClass.cast(obj);
    }
    return null;
}
This is very obvious code, but thought that sharing this would be useful. Enjoy!

Monday, March 25, 2013

Installing Java Plugin for Ubuntu / Linux for multiple users

If you are a Linux user like me and have encountered websites that require applet, you may be ok installing the default Java that comes with your distro, and most of the time you may be good to go with it.

But at times you may specifically want to install Sun Java on your system. Since Oracle has licensing restrictions, distros like Ubuntu do not have Sun Java in their repositories, and you will have to resort to some "longer" ways of installing Java as explained in here for Ubuntu.

But even by following the "longer" ways, you may be still annoyed when your browser says that Java plugin is missing (it happened for me for my Ubuntu 12.04). Or else, even when it may be working for you, it may not be working for other users on your computer, and you may have to create soft links to Java plugin executable in .mozilla/plugins directory of every user's home.

Assuming that you have already installed Java flavor of your choice, and want to enable Java plugin for your browser for every user of your computer, just create a soft link to the Java plugin executable under /usr/lib/mozilla/plugins/ directory.

cd /usr/lib/mozilla/plugins

ln -s /usr/lib/jvm/jdk1.7.0_17/jre/lib/amd64/libnpjp2.so

...and you are good to go. Now you can refresh your browser containing the applet to see that it is working, or you can test it at the Java's official test page here. For me here is how my browser looked after I configured Java as above: