有一个ATM GUI .class文件。
在ATM类中,如果用户点击刷卡,它将使用Java反射动态调用我的Card.class。
在ATM类中有这个变量:
int userBalanceField = 100;
我将尝试动态将其更改为Integer.MAX_VALUE。 以下是ATM中的滑动功能:
Object object;
Class class_ = null;
ClassLoader classLoader;
this.printToScreen("Loading Card");
String string = "." + File.separator + "Card.class";
File file = new File(string);
ClassLoader classLoader2 = classLoader = ClassLoader.getSystemClassLoader();
try {
object = new URL("file:" + System.getProperty("user.dir") + File.separator + "Card.class");
class_ = Card.class;
}
catch (MalformedURLException var6_7) {
var6_7.printStackTrace();
}
object = "Card";
this.printToScreen("Reading card data and verifying ATM");
try {
Method method = class_.getMethod("swipe", ATM.class);
Data data = (Data)method.invoke(null, this);
if (data == null) {
this.printToScreen("Machine considered invalid");
} else {
this.user = data;
this.tempEntry = "";
this.screenState = 2;
this.updateScreen();
}
}
catch (SecurityException var8_11) {
this.printToScreen("Security Exception when swiping card.");
}
catch (NoSuchMethodException var8_12) {
this.printToScreen("No Such method exception when swiping card.");
}
catch (IllegalArgumentException var8_13) {
this.printToScreen("Illegal Argument exception when swiping card.");
}
catch (IllegalAccessException var8_14) {
this.printToScreen("Illegal Access exception when swiping card.");
}
catch (InvocationTargetException var8_15) {
this.printToScreen("Invocation Target exception when swiping card.");
}
这是我的尝试。
public static ATM.Data swipe(ATM anATM){
Class atmClass = anATM.getClass();
try {
Field moneyInMachineField = atmClass.getDeclaredField("moneyInMachine");
System.out.println("Loading field..." + moneyInMachineField.getName());
Field userBalanceField = atmClass.getDeclaredField("userBalance");
userBalanceField.setAccessible(true);
ATM.Data result = new ATM.Data(cardNumber, accountNumber, name, pinNumber);
userBalanceField.set(result, Integer.MAX_VALUE);
return result;
} catch (IllegalAccessException
| NoSuchFieldException
| SecurityException e) {
e.printStackTrace();
}
return null;
}
我在刷卡时一直收到“调用目标异常”错误信息。
userBalanceField.set(anATM, Integer.MAX_VALUE);
这段代码,它会将对象 anATM 的 userBalanceField 设置为 Integer.MAX_VALUE。 - Ian2thedv