Java and Java Beans help...

Associate
Joined
24 Jun 2007
Posts
1,869
Location
Landan.
Edit: Posted full source below

Evening all,

I'm creating an app that makes use of a JavaBean for some separate functions. However, I have a problem whereby the JavaBean's main constructor can throw a ClassNotFoundException, but when I come to use it in my main app I want to create and initialise outside (and above) main so that it can be used throughout the app.

Perhaps it'd be easier to show it in code:

The JavaBean

Code:
public class OrderHandling
                implements java.io.Serializable
{
    private static final long serialVersionUID = 1L;


    public OrderHandling() throws ClassNotFoundException
    {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        }
        catch (ClassNotFoundException cnfEx)
        {
            throw new ClassNotFoundException(
                        "Unable to locate JDBC driver!");
        }
    }

//Functions follow...
The main app:

Code:
public class MenuSystem {

    private static int option;
    public OrderHandling calcOrder = new [U]OrderHandling[/U]();
    
    public static void main (String[] args)
    {
        <-- Do stuff -->
     }
I've underlined what Eclipse underlines, and gives the error:

Default constructor cannot handle exception type ClassNotFoundException thrown by implicit super constructor. Must define an explicit constructor
So I get that, the bean throws the exception, and my app doesn't know what to do with it.

So - how do I somehow work throws ClassNotFoundException into the declaration and creation of the OrderHandling class? :confused:

Any help or pointers would be greatly received :)

Thanks!
 
Last edited:
Could you put it (the new OrderHandling() assignment) in a try catch block in the MenuSystem constructor or the main method? Otherwise the exception is thrown while the class is actually initialising and probably can't run.

Don't know whether you can have a try catch block outside of a method - will give it a go! Thanks
icon14.gif
 
Sorry, subclasses, anything that extends it.

Sorry for the delay in response, my broadband has been playing up over the past few days.

To answer your question, afaik (that is, presuming I'm not being stupid), no it doesn't. Just functions/methods within the class.

Thanks again :)

To add to the other posters question: I've tried a try catch block outside of any methods, but it doesn't seem to be having it :(
 
You want to access the object in the main() function?

Usually the main function just passes control, to objects. Since main is static it can only access class(static) fields, not object fields.

So the OrderHandling object has to be static to.

Keep the method reference outside the main method, but create the object in main method, that way main creates it but it's still globally accessible within that class.

Code:
public class Main {

    public static OrderClass orderClass;
    
    public static void main(String[] args) {
        try {
            orderClass = new OrderClass();
        } catch (ClassNotFoundException e) {
            System.err.println("Something messed up");
            e.printStackTrace();
        }

    }

}
Since main is guaranteed to run, it always going to initialized
Is that you mean ?

Thats not how i would do it though. I'd create a application controller object, and do this stuff in its constructor. Thats what there for.

According to my instructions (from my lecturer (yes, the truth will out: this is for an assignment :o)) - "Place both the declaration and creation of this bean above main, so that is can be accessed from anywhere in the program".

If it wouldn't have been for that snippet - I would have already done as you had suggested :( Hence the confusion really.

Would it be possible for you to expand on:

Thats not how i would do it though. I'd create a application controller object, and do this stuff in its constructor. Thats exactly what there for.
?

Thanks for the reply, and if all else fails, I'll go with that
icon14.gif
 
I would create a Factory to get my order handling objects from. with something like.

OrderHandlingFactory.getHandler();

Objects can be then created on call, throw exceptions if it fails, otherwise returned.

Unfortunately I've been told to do it as above, been staring at the screen for a few hours now trying different things - I'm beginning to suspect that he's misworded the instructions.

Might post over on the java forums to see if there's any one feeling kind :)
 
Thanks to a couple of friends I've now sort of resolved this. I was getting the error because the Class superconstructor couldn't handle the CnfEx - so I had to explicitly define the Main class's constructor, with the relevant throws statement.

The class that makes use of the OrderHandling bean now looks like:

Code:
public class MenuSystem {

    private static final long serialVersionUID = 1L;
    private static int option;

    public OrderHandling calcOrder = new OrderHandling();
    
    public MenuSystem() throws ClassNotFoundException
    {
        
    }
However, for some reason, if I design the code to ensure a CnfEx is definitely thrown, it never is - that is, an error never appears when the OrderHandling bean looks like:

Code:
public class OrderHandling
                implements java.io.Serializable
{
    private static final long serialVersionUID = 1L;


    public OrderHandling() throws ClassNotFoundException
    {
        try
        {
            Class.forName("[B]bleurgh[/B]");
        }
        catch (ClassNotFoundException cnfEx)
        {
            throw new ClassNotFoundException(
                        "Unable to locate JDBC driver!");
        }
I've also altered the Main class code in an attempt to throw the error so it looks like:

Code:
public class Main {

    private static final long serialVersionUID = 1L;
    private static int option;

    public OrderHandling calcOrder;
    
    public MenuSystem()
    {
        System.out.println("Herro");
        try {
                calcOrder = new OrderHandling();
                System.out.println("Bye");
            }
        catch(ClassNotFoundException cnfEx)
            {
                System.out.println(cnfEx);
                System.exit(0);
            }
    }
    }

Still with no error being thrown - its as if the constructor within main is never being called when the class is being initialized. :( Anyone got any ideas?

Thanks :)
 
Where is the constructor in Main?

You have public MenuSystem() declared in Main which is neither a valid method declaration (no return type defined) or a vaild constructor for the Main class(it's not called Main()).

Sorry - Main = MenuSystem :)

I edited it to try and make it a little more readable, and failed :o

Here's the full thing, with no editing :) :

Code:
package stockApp;

import java.util.*;
import stockBeans.OrderHandling;

public class MenuSystem {

    private static final long serialVersionUID = 1L;
    private static int option;

    public OrderHandling calcOrder = new OrderHandling();
    
    public MenuSystem()
    {

    }

    
    public static void main (String[] args)
    {
        String entry;
        
        
        // Generate the menu and accept users option
        
        do
        {
            displayMenu();
            System.out.println("\nPlease select a menu option:");
            Scanner input = new Scanner(System.in);
            entry = input.nextLine();
            option = entry.charAt(0);
    
            switch (option)
            {
                case '1': retrieveLevel();
                            break;
                case '2': displayStock();
                            break;
                case '3': calculateOrder();
                            break;
                case '4': newOrder();
                            break;
                case '5': branchOrders();
                            break;
                case '0': return;    
                            
                default: System.out.println("\n\t\tInvalid entry! Try again.\n");
                            break;
            }
            
        } while (option != 0);
    }
    
    private static void displayMenu()
    {
        
        System.out.println("\t :: Stock Manager v1.1 ::\n");
        System.out.println("\t\t1. Retrieve item stock level.");
        System.out.println("\t\t2. Display stock list.");
        System.out.println("\t\t3. Calculate order value.");
        System.out.println("\t\t4. Place a new order.");
        System.out.println("\t\t5. Display this branches orders.");
        System.out.println("\t\t0. Exit.");
    }
    
    private static void retrieveLevel()
    {
        System.out.println("\nYou have chosen Option 1.\n");
    }
    
    private static void displayStock()
    {
        System.out.println("\nYou have chosen Option 2.\n");
    }
    
    private static void calculateOrder()
    {
        System.out.println("\nYou have chosen Option 3.\n");
    }
    
    private static void newOrder()
    {
        System.out.println("\nYou have chosen Option 4.\n");
    }
    
    private static void branchOrders()
    {
        System.out.println("\nYou have chosen option number 5");
    }
}

The edited region of MenuSystem where I was trying to see why an error wasn't being generated as per my last post (complete with numerous print statements to aid in debugging :o):

Code:
public class MenuSystem {

    private static final long serialVersionUID = 1L;
    private static int option;

    public OrderHandling calcOrder;
    
    public MenuSystem()
    {
        System.out.println("Herro");
        try {
                calcOrder = new OrderHandling();
                System.out.println("Bye");
            }
        catch(ClassNotFoundException cnfEx)
            {
                System.out.println(cnfEx);
                System.exit(0);
            }
    }
And here's the Bean in full:

Code:
package stockBeans;
import java.sql.*;
import java.net.*;
import java.util.*;

public class OrderHandling
                implements java.io.Serializable
{

    
    
    
    private static final long serialVersionUID = 1L;
    private Connection connection;
    private Statement statement;
    private ResultSet results;

    public OrderHandling() throws ClassNotFoundException
    {
        try
        {
            System.out.println("OrderHandling is in use");
            Class.forName("bleugh");
        }
        catch (ClassNotFoundException cnfEx)
        {
            throw new ClassNotFoundException(
                        "Unable to locate JDBC driver!");
        }
    }

    public float getCost(String stockCode,
                        int quantity) throws SQLException
    {
        float orderCost = 0;
        String query =
            "SELECT price FROM StockItems WHERE stockCode = '"
            + stockCode + "'";

        connectAndCreateStatement();

        results = statement.executeQuery(query);
        if (results.next())
            orderCost = results.getFloat(1) * quantity;
        disconnectFromDb();

        return orderCost;
    }

    public Vector<Vector<Object>> getOrders(int branchNumber)
                                            throws SQLException
    {
        Vector<Object> orderRow;
        Vector<Vector<Object>> branchOrders;
        String query =
            "SELECT orderNumber, orderDate, stockCode, quantity"
            + " FROM StockOrders WHERE branchCode = "
            + branchNumber;
        connectAndCreateStatement();

        branchOrders = new Vector<Vector<Object>>();

        results = statement.executeQuery(query);
        while (results.next())
        {
            orderRow = new Vector<Object>();
            orderRow.add(results.getInt(1));
            orderRow.add(results.getDate(2));
            orderRow.add(results.getString(3));
            orderRow.add(results.getInt(4));
            branchOrders.add(orderRow);
        }
        disconnectFromDb();

        return branchOrders;
    }

    private void connectAndCreateStatement() throws SQLException
    {
        try
        {
            connection = DriverManager.getConnection(
                                    "jdbc:odbc:Stock","","");
            //* Change DSN (Data Source Name) if yours is different! *
        }
        catch (SQLException sqlEx)
        {
            throw new SQLException("Unable to connect to database!");
        }

        try
        {
            statement = connection.createStatement();
        }
        catch (SQLException sqlEx)
        {
            throw new SQLException("Unable to create SQL statement!");
        }
    }


    private void disconnectFromDb() throws SQLException
    {
        try
        {
            connection.close();
        }
        catch (SQLException sqlEx)
        {
            throw new SQLException(
                    "Unable to disconnect from database!");
        }
    }
}
I was trying to avoid posting the full source to not put people off helping, but may as well now :)

Thanks for looking
icon14.gif
 
Last edited:
Back
Top Bottom