Wednesday, July 15, 2015

URL based class loading in Java and dynamically adding directories to java classpath @ runtime

1. How to load a class dynamically at runtime by using URLClassLoader .

// Main Method
        try { 
            URL url = new URL("file:///<path to my jar file>.jar");
            URLClassLoader urlClassLoader = new URLClassLoader(
                    new URL[] { url });
            Class clazz = urlClassLoader
                    .loadClass("org.sample.package.ClassName");
            Object obj = clazz.newInstance();
            System.out.println(obj.toString());
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

Explanation:

Create a URL object of the jar file 
Pass the URL object to the URLClassLoader
Call loadCLass on the URLClassLoader object , specifying the class name with the package hierarchy , as argument.
Create a new Instance of the loadedClass
Refer to newInstance()for more details.
Use the obj of the loaded class to call a method.

Exceptions to be handled:

IllegalAccessException - if the class or its nullary constructor is not accessible.

InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.

ClassNotFoundException - If the class was not found

MalformedURLException - if an unknown protocol is specified.

                                   ###########################################

2. How to dynamically add directories from a fileSystem to Java ClassPath @ Runtime 

// Main Method
        try {
            File file = new File("absolute/path/to/the/directory");
            Method method = URLClassLoader.class.getDeclared
                  Method("addURL", new Class[] { URL.class});
            method.setAccessible(true);
            method.invoke(ClassLoader.getSystemClassLoader(),
                    new Object[] { file.toURI().toURL() });
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

Explanation:

Create a file object for the directory to be added to the classpath.
Get the method object of addUrl method of the class URLClassLoader
For more details see this.
Reflected object should suppress Java language access Checking when it is used , hence the setAccessible(true).
Invoke the method , the first argument is the class invoking the method and the following arguments are sent as arguments to the invoked method in orderly fashion. 

Exceptions to be handled:

NoSuchMethodException - if a matching method is not found.

SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException 

Refer this

MalformedURLException - if an unknown protocol is specified.

I hope you learned something new today .

Saturday, July 11, 2015

How to install Sublime text editor using apt-get on Linux using PPA

Sublime Text is one of the most popular editors and my favorite for writing computer Programs in various languages . Now if you are windows user , its not pretty difficult to download and install this editor simply click here and download the required version and install.

Also this link can help you download the Linux binaries but  guess what you are not the unzip candidate who wants to keep binaries in a directory and add that to you unix / linux PATH . You are the apt-get guy .

So what to do then , simply follow these steps

So what to do then , simply follow these steps

### add sublime ppa to repository ###


sudo add-apt-repository ppa:webupd8team/sublime-text-2

Repository maintained by  webupd8 team.

### update ###

sudo apt-get update

### install ###

sudo apt-get install sublime-text

### check installed version ###

anmol@anmol-Studio-1555:~/sw$ sublime-text -v
Sublime Text 2 Build 2221

Enjoy 

How to install / upgrade to JAVA 8 (JDK 8u45) on Ubuntu & LinuxMint using PPA

Oracle JAVA 8 Stable release has been released on Mar,18 2014 and can be downloaded and installed from Oracle Java downloads . Oracle Java PPA for Ubuntu and LinuxMint is being maintained by WebUpd8 .
 
Read about the new features about Java 8 here .

This article will help you to Install Oracle JAVA 8 (JDK/JRE 8u25) on Ubuntu 14.04 LTS, 12.04 LTS and 10.04 and LinuxMint systems using PPA File.

Installing Java 8 on Ubuntu

Add the webupd8team Java PPA repository in your system and install Oracle Java 8 using following set of commands.


$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo apt-get install oracle-java8-installer

Verify Installed Java Version

After successfully installing oracle Java using above step verify installed version using following command.

anmol@anmol-Studio-1555:~$ java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)  

Configuring Java Environment 

In Webupd8 ppa repository also providing a package to set environment variables, Install this package using following command.

$ sudo apt-get install oracle-java8-set-default 
 
References :

https://launchpad.net/~webupd8team/+archive/ubuntu/java
http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html