OO Programming in Java

Class 6 Material


Class.forName

Class.forName can instantiate classes given a string.


Example:

An application was completed and released for beta testing. Users found that they liked the compactness of the existing GUI but wanted it to look like a telephone. This was made an option, BigView looked like a telephone, LittleView used buttons only.


First let's look at the Configuration file .....

#Bernie Environment Settings
#Sat Jun 28 12:08:40  1997
SERVER=Bernie
SENDER=poliquin
MAILHOST=cats.ucsc.edu
PASSWORD=casablanca
PROVIDER=softcomp.com
SLIPPATH=c:\\bernard\\slips.dat
VIEW=LittleView


Code fragment from 'main'

        String viewName = Configuration.instance().valueOf("VIEW");
        try {
            theView = ((View) ((Class.forName(viewName)).newInstance()));
        }
        catch (InstantiationException e)
            {System.out.println("View Creation Error InstantiationException"); }
        catch (ClassNotFoundException e)
            {System.out.println("View Creation Error ClassNotFoundException"); }
        catch (IllegalAccessException e)
            {System.out.println("View Creation Error IllegalAccessException"); }

viewName has the String "LittleView" from the Configuration file.

theView ends up with an instance of LittleView. Several exceptions can be thrown:

InstantiationException - interface or abstract class

ClassNotFoundException - no definition of the class could be found

IllegalAccessException - class is not publiuc and in another package.


Code changes:

The original view was subclassed .. with BigView, and LittleView


class BigView extends View {


    public void initialize(String aName){
        this.widgets(new Hashtable());
        this.widgets().put(aName,this);
        this.setLayout(null);
        this.theImage = Toolkit.getDefaultToolkit().
                            getImage("c:\\bernard\\pix\\bigBack.GIF");
.
.
class LittleView extends View{

    public void initialize(String aName){
        this.widgets(new Hashtable());
        this.widgets().put(aName,this);
        this.setLayout(null);
        this.theImage = Toolkit.getDefaultToolkit().
                            getImage("c:\\bernard\\pix\\littleBack.GIF");
.
.
.
.
Only one method needed to be changed, initialize.