jeudi 28 avril 2016

How to change an ATM class during run time (Java Reflection)

There is an ATM GUI .class.

In the ATM class, if the user click swipe, it will use Java reflection to dynamically call my Card.class.

In the ATM class there is this variable:

int userBalanceField = 100;

I am trying to dynamically change it to Integer.MAX_VALUE.That being said, I successfully changed the value because I print the value. However, when the ATM program starts, userBalanceField is still set at 100.

What am I doing wrong?

public static ATM.Data swipe(ATM anATM) {       

    Class atmClass = anATM.getClass();
    System.out.println("Creating atmClass:" + atmClass.getName());
    try {
        Object o = atmClass.newInstance();
        System.out.println("Creating new object...");
        Field moneyInMachineField = atmClass.getDeclaredField("moneyInMachine");
        moneyInMachineField.setAccessible(true);

        System.out.println("Loading field..." + moneyInMachineField.getName());

        Field userBalanceField = atmClass.getDeclaredField("userBalance");
        userBalanceField.setAccessible(true);

        System.out.println("Creating userBalanceField..." + userBalanceField.getName());
        userBalanceField.set(o, Integer.MAX_VALUE);
        System.out.println(userBalanceField.get(o));

    } catch (InstantiationException 
            | IllegalAccessException 
            | NoSuchFieldException 
            | SecurityException e) {
        e.printStackTrace();
    }

    return new ATM.Data(cardNumber, accountNumber, name, pinNumber);

}

Source code to ATM: http://ift.tt/1N5b62P





Aucun commentaire:

Enregistrer un commentaire