CS351 Spring 2004 Lab 8

Inner Classes, a Review


Two very different Things
When we are talk about inner classes, we are referring to class which are defined inside of another class. The inner class is said to be enclosed by the outer class.

	class Outer{
	{
		class Inner{}
	}
Using a JAR file

The JRE has built-in support for JAR files, to use a JAR file called test.jar and execute the class Hello you would use the command:
	java -cp test.jar Hello
		
If the JAR has a manifest file that specifies what class to execute (we'll discuss that in a moment), you just have to say:
	java -jar test.jar
		
Creating a JAR File

See the man page for JAR for advanced options.

The commandline for the program jar is based on tar. To create a JAR file test.jar with all the class files in the current directory:

	jar cvf test.jar *.class
	
To look at the contents of a jar file:
	jar tvf test.jar
	
To update a jar file:
	jar uvf test.jar file_to_add.class
	
What's a Manifest File

There is a special file that can be included inside of a jar file. It is always called:
 META-INF/MANIFEST.MF
(Don't worry about the name/location, jar takes care of the details for you).

This file can do a lot of things, such as specifing signatures and versioning information. The one item we're particularly interested in is specifying the main class.

Default Manifest file:

	Manifest-Version: 1.0

To specify the main class, create a text file that looks like this:

	Manifest-Version: 1.0
	Main-Class: Hello
Then when creating your JAR file, you specifiy the manifest file to (named manifest_file in example):
	jar cvmf manifest_file test.jar Hello.class
	
Some simple Reflection

Reflection is a mechanism in Java that allows us to write programs that do things with Java class files. Many complex things can be done with these facilities. See the Reflection Trail for more information.

An easy thing to do is given a class name "myClass", to instantiate an instance of it using the default constructor:

	try{
		Class classObject = Class.forName("myClass");
		Object object = classObject.newInstance();
	} catch (InstantiationException e) {
		System.out.println(e);
	} catch (IllegalAccessException e) {
		System.out.println(e);
	} catch (ClassNotFoundException e) {
		System.out.println(e);
	}
	
Notice all the exceptions. Lots of things can go wrong. But using this mechanism it is relatively easy to have your program load arbitrary plug-in class at load-time.

You're not going to be required to use Reflection in this class, but it is a very powerful tool that we want you to be aware of. Feel free to use it to add functionality to your class projects.

Exercise

Create a simple Java program that prints out "Hello World", package it into a jar file called hello.jar such that it can be execute with the command:
	java -jar hello.jar
	
Due by the end of class.