如何通过Java反射使此布尔语句为false
我必须使用反射 在我的ATM类中,我有两个变量:如何通过Java反射使此布尔语句为false,java,reflection,Java,Reflection,我必须使用反射 在我的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 ca
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();
}
private void宽度提取金额(int n){
if(this.userBalance-n<0 | | this.moneyInMachine-n<0){
//你不能把钱拿出来。
}
this.updateScreen();
}
我想知道是否有人知道一种方法可以让boolea的陈述是错误的。试试这个:
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);
试试这个:
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);
您只能更改字段的值,不能更改代码的语句 此代码:
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
这意味着您甚至可以使用反射来更改私有变量的值。您只能更改字段的值,而不能更改代码的语句 此代码:
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
这意味着您甚至可以使用反射更改私有变量的值。您不能使用反射,因为反射是编译代码。使用反射,您只能调用方法、更改字段值等,但不能更改代码本身。这里使用反射的唯一方法是将
userBalance
和moneyInMachine
更改为至少等于n
。您不能使用反射,因为这是编译代码。使用反射,您只能调用方法、更改字段值等,但不能更改代码本身。这里使用反射的唯一方法是将userBalance
和moneyInMachine
更改为至少等于n
。哇,有人要发财了,哈哈。哇,有人要发财了,哈哈。