Saturday, September 1, 2012

How to create Extensible Application in Java

import java.io.* ;

class Store {
    int x ;

    void write(String data) {
        x = 10 ;
    }

    String read( ) {
        x = 10 ;
        return "Cannot read." ;
    }
}

class FileStore extends Store {

    int y ;

    void write ( String data ) {
        System.out.println ( data + " written to the file" ) ;
    }

    String read( ) {
        return "Hello read from the file" ;
    }
}

class DatabaseStore extends Store {

    int z ;

    void write ( String data ) {
        System.out.println ( data + " written to the database" ) ;
    }
}

class DynamicArray {
    String items[ ] = new String[0] ;

    void add ( String item ) {
        String temp[] = new String[items.length+1] ;
        for ( int i = 0 ; i < items.length ; i++ ) {
            temp[i] = items[i] ;
        }
        items = temp ;
        items[items.length-1] = item ;
    }
   
    int getCount( ) {
        return items.length ;
    }

    String getItem ( int index ) {
        return items[index] ;
    }
}

class UserInteraction {
    Store takeInput( ) {
        DynamicArray names = new DynamicArray( ) ;
        try {
        File f = new File(".") ; // current directory
        String[] files = f.list( ) ; // get all the files
        for ( int i = 0 ; i < files.length ; i++ )  {
            if ( files[i].contains(".class") ) { // get only .class files
                Class c = Class.forName ( files[i].split(".class")[0] ) ;
                if ( c.getSuperclass().getName().equals( "Store" ) ) 
                    names.add ( files[i].split(".class")[0] ) ;
            }

        }

        // Display the menu....
        for ( int i = 0 ; i < names.getCount() ; i++ ) {
            System.out.println ( (i+1) + ": " + names.getItem(i) ) ;
        }

        java.util.Scanner scan = new java.util.Scanner(System.in) ;
        int choice = scan.nextInt() ;

        Class c = Class.forName ( names.getItem(choice-1)) ;
        return (Store) c.newInstance( ) ;
        } catch ( Exception ex ) {
            System.out.println ( ex ) ;
            return null ;
        }
    }
}

class Program { 
    public static void main ( String[] args )  {
        UserInteraction ui = new UserInteraction( ) ;
        Store  f =     ui.takeInput( ) ;
        f.write ( "Hello" ) ;
        String item = f.read( ) ;
        System.out.println ( item ) ;
    }
}


class XMLStore extends Store {
    void write ( String data ) {
        System.out.println ( data + " written to XML file." ) ;
    }
    String read( ) {
        return "Hello read from the XML file" ;
    }
}

No comments:

Post a Comment