2016-04-21 64 views
0

我必须使用反射。如何通过Java反射使此布尔语句为false

在我的ATM类我有两个变量:

private int userBalance = 100; 
    private int moneyInMachine = 100000; 

我想撤回资金无限量。

这里是ATM的退出功能:

private void widthdrawAmount(int n) { 
    if (this.userBalance - n < 0 || this.moneyInMachine - n < 0) { 
     // You can not pull money out. 
    } 

    this.updateScreen(); 
} 

我不知道是否有人知道的方式来利用这个boolea说法错误的。

+0

你不能使用反射来做这件事,因为这是编译代码。使用反射只能调用方法,更改字段值等,但不能更改代码本身。这里使用反射的唯一方法是将'userBalance'和'moneyInMachine'改为至少等于'n'。 – Thomas

回答

3

试试这个:

Field userBalance = myAtm.getClass().getDeclaredField("userBalance"); 
userBalance.setAccessible(true); 
userBalance.set(myAtm, Integer.MAX_VALUE); 

Field moneyInMachine = myAtm.getClass().getDeclaredField("moneyInMachine"); 
moneyInMachine.setAccessible(true); 
moneyInMachine.set(myAtm, Integer.MAX_VALUE); 
+0

哇,有人会变得富有,哈哈。 – user6212007

1

您只能更改的字段,你的代码不是语句的值。

此代码:

public static class ATM { 
    private int userBalance = 100; 
    private int moneyInMachine = 100000; 
    public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { 
    ATM a = new ATM(); 
    Field balanceField = ATM.class.getDeclaredField("userBalance"); 
    balanceField.setAccessible(true); 
    balanceField.set(a, 123456); 
    System.out.println(a.userBalance); 
    } 
} 

打印

123456

这意味着,你可以改变使用反射甚至私有变量的值。