Calling URL Browser From Java Application

This program teaches you how you can call the browser in your OS to open the URL that you are passing from your Java application. This program is fully compiled and tested.

package com.kushal.utilities;

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 26th August, 2008
 */
import java.lang.reflect.Method;

import javax.swing.JOptionPane;

public class OpenDefaultBrowserFromJava {
	private static final String errMsg = "ERROR WHILE ATTEMPTEING TO LUNCH WEB BROWSER";
	private static final String errFindingBrowser="COULD NOT FIND THE BROWSER";
	
	public static void main(String args [])
	{
		String urlToOpen="http://www.sanjaal.com/java";
		openURL(urlToOpen);
	}

	/**
	 * This method takes URL as a parameter and tries to
	 * identify Operating system and then lunches the broswer
	 * with the given URL
	 */
	public static void openURL(String url) {
		String operatingSystem = System.getProperty("os.name");
		try {
			/*
			 * Check if it is windows OS 
			 */
			if (operatingSystem.startsWith("Windows"))
				Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
			/*
			 * If not windows OS, Check if it is a Mac OS
			 */
			else if (operatingSystem.startsWith("Mac OS")) {
				Class fileManager = Class.forName("com.apple.eio.FileManager");
				Method openURL = fileManager.getDeclaredMethod("openURL",
						new Class[] { String.class });
				openURL.invoke(null, new Object[] { url });
			}
			
			/*
			 * Or, it might be some unix or linux OS
			 */
			else { 
				/**
				 * There are different browsers possible.
				 */
				String[] browsers = { 	"firefox", 
										"netscape",
										"opera", 
										"konqueror", 
										"epiphany", 
										"mozilla"};
				String browser = null;
				
				for (int count = 0; count < browsers.length && browser == null; count++)
					if (Runtime.getRuntime().exec(
							new String[] { "which", browsers[count] })
							.waitFor() == 0)
						browser = browsers[count];

				if (browser == null) 
					throw new Exception(errFindingBrowser);
				else
					Runtime.getRuntime().exec(new String[] { browser, url });
			}

		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, errMsg + ":n" + e.getMessage());
		}
	}

}

Java Reflections Tutorial

This tutorial gives an insight on how Java Reflection can be used to load Java classes dynamically at the run time. Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

package com.kushal.utilities;

/**
 * @author Kushal Paudyal
 * 08/05/2008
 * 
 * Simple demonstration of Java Reflection mechanism to
 * instantiate a class, get it's method and call that
 * method with proper parameter passing.
 */
import java.lang.reflect.*;

public class JavaReflectionsDemo {

	public static void main(String args[]) {
		try {
			/*
			 * Step 1 Define a class loader
			 */
			ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
			/*
			 * Step 2: Define a class to be loaded.
			 */
			String classNameToBeLoaded = "com.kushal.utilities.DemoClassToBeLoaded";

			/*
			 * Step 3: Load the class
			 */
			Class myClass = myClassLoader.loadClass(classNameToBeLoaded);

			/*
			 *Step 4: create a new instance of that class
			 */
			Object whatInstance = myClass.newInstance();

			String methodParameter = "ABC";
			/*
			 * Step 5: get the method, with proper parameter signature.
			 * The second parameter is the parameter type.
			 * There can be multiple parameters for the method we are trying to call, 
			 * hence the use of array.
			 */

			Method myMethod = myClass.getMethod("myMethod123",
					new Class[] { String.class });

			/*
			 *Step 6:
			 *Calling the real method. Passing methodParameter as
			 *parameter. You can pass multiple paramters based on 
			 *the signature of the method you are calling. Hence
			 *there is an array. 
			 */
			String returnValue = (String) myMethod.invoke(whatInstance,
					new Object[] { methodParameter });

			System.out.println("The value returned from the method is:"
					+ returnValue);

			/*
			 * Catching Probable Exceptions
			 * You can simply catch the Generic 'Exception' to reduce your coding.		 
			 */
		} catch (ClassNotFoundException e1) {
			System.out.println("EXCEPTION:CLASS NOT FOUND");
		} catch (IllegalAccessException e2) {
			System.out.println("EXCEPTION:ILLEGAL ACCESS");
		} catch (InstantiationException e3) {
			System.out.println("EXCEPTION:INSTANTIATION EXCEPTION");
		} catch (NoSuchMethodException e4) {
			System.out.println("EXCEPTION:NO SUCH METHOD");
		} catch (InvocationTargetException e5) {
			System.out.println("EXCEPTION: INVOCATION TARGET");

		}
	}

}
/**
 * @author Kushal Paudyal
 * 08/05/2008
 * www.sanjaal.com/java
 */

/*
 * This is the demo class that we will use to load and invoke method
 * using Java Reflection.
 */
class DemoClassToBeLoaded {
	public static String myMethod123(String someParam) {
		System.out.println("You Are Calling myMethod()");
		System.out.println("You Passed " + someParam + " as Parameter");

		/*
		 * Just returning the current class name
		 * This is just an example method. 
		 */
		return DemoClassToBeLoaded.class.getName();
	}

}