Java Bean零点异常&调用目标异常

时间:2014-11-20 04:13:30

标签: java nullpointerexception javabeans invocationtargetexception

我正在使用以下bean获得空点异常和调用目标异常。该计划主要是测试存款和取款的余额,还包括交易ID。我在客户端代码中得到了这些例外。

import BankBeanRemotePkg.BankBeanRemote;
import javax.ejb.Stateful;
import java.math.BigDecimal;
import java.util.Random;
import javax.ejb.Remote;
import javax.interceptor.Interceptors;

/**
 *
 * @author Aneel
 */
@Stateful
@Remote(BankBeanRemotePkg.BankBeanRemote.class)
@Interceptors(BankBeanPkg.BankCallBacks.class)

public class BankBean implements BankBeanRemote {

    private BigDecimal balance;
    @Override
    public BigDecimal initial() {
        BigDecimal initialbal = new BigDecimal("0.00");
        return initialbal.setScale(2, BigDecimal.ROUND_UP);
    }

    @Override
    public BigDecimal Current() {
        return balance.setScale(2, BigDecimal.ROUND_UP);
    }

    @Override
    public int Deposit(BigDecimal amt) {
        BigDecimal updatedBal = amt.add(balance);
        balance = updatedBal;
        Random randomGenerator = new Random();
        int randomID = randomGenerator.nextInt(1000);
        return randomID;
    }

    @Override
    public int Withdraw(BigDecimal amt) {
        BigDecimal updatedBal = balance.subtract(amt);
        balance = updatedBal;
        Random randomGenerator = new Random();
        int randomID = randomGenerator.nextInt(1000);
        return randomID;
    }
}

仅测试简单银行交易的客户端代码是:

import BankBeanRemotePkg.BankBeanRemote;
import java.math.BigDecimal;


public class BankClient {

    private static BankBeanRemote bankBean;
    public BankClient (String[] args) {
    }

    public static void main(String[] args) {
        BankClient client = new BankClient(args);
        client.test();
    }

    public void test(){
        try {
            BigDecimal initial = bankBean.initial();
            System.out.println("Initial Balance:" + initial);
            BigDecimal deposit = new BigDecimal("5.00");
            int transactionid = bankBean.Deposit(deposit);
            System.out.println("Deposit amt:" + deposit + "Transaction ID:" + transactionid);
            BigDecimal balance = bankBean.Current();
            System.out.println("Current Balance:" + balance);
            BigDecimal withdraw = new BigDecimal("3.00");
            int transactionid2 = bankBean.Withdraw(withdraw);
            System.out.println("Withdraw amt:" + withdraw + "Transaction ID:" + transactionid2);
            System.out.println("Current Balance:" + balance);
        } catch (Exception ex) {
            System.err.println("Caught an unexpected exception!");
        }

    }
}

任何人都知道如何修复我的代码?

由于

1 个答案:

答案 0 :(得分:0)

在调用bankBean方法之前,您没有正确地实例化initial()。你必须做这样的事情:

// Obtain InitialContext (ctx) object
BankBeanRemote bankBean = ctx.lookup("BankBean");
....
BigDecimal initial = bankBean.initial();

这应该摆脱你的NPE。