How do I replace a value in a method with ExprEditor?

50 Views Asked by At

I am trying to modify the value in the code from 2.0 to 1.0 with expreditor. Nested if statements under a method "alterSkill"

if (player2.hasSleepBonus()) {
advanceMultiplicator *= 2.0;}

I've got a utility someone else wrote

        public static void instrumentDescribed(Class<?> instrumentingClass, CtClass ctToInstrument, String declaredMethod, String descriptor, String methodCall, String replace){
        try {
            ctToInstrument.getMethod(declaredMethod, descriptor).instrument(new ExprEditor(){
                public void edit(MethodCall m) throws CannotCompileException {
                    if (m.getMethodName().equals(methodCall)) {
                        m.replace(replace);
                        success = true;
                    }
                }
            });
            checkSuccess(0, instrumentingClass, ctToInstrument, declaredMethod, methodCall);
        } catch (CannotCompileException | NotFoundException e) {
            //e.printStackTrace();
            checkSuccess(0, instrumentingClass, ctToInstrument, declaredMethod, methodCall);
            logger.severe(e.getMessage());
        }
    }

My code:

if (reduceSleepBonus) {
    Util.setReason("Change sleep powder from 2x to 1.0x");
    replace = "advanceMultiplicator *= 1.0;" +
              "$_ = $proceed($$);";
    Util.instrumentDescribed(thisClass, ctSkill, "alterSkill", desc4, "hasSleepBonus", replace);
    }

My program is saying it has been successfully implemented. However my suspicion is that it is simply setting advanceMultiplicator to 1.0 and not modifying the 2.0 to 1.0. I have tested it in the program and confirmed that the skill is being doubled when hasSleepBonus() is true.

1

There are 1 best solutions below

0
On

Using the aforementioned utility it was just an issue of putting the right code in the replace string. The original code took advanceMultiplicator and just multiplied it by 1.0 which did nothing and did not access the field.

if (reduceSleepBonus) {
    Util.setReason("Change sleep powder from 2.0 to 1.0");
    replace = "if($proceed($$)){ advanceMultiplicator *= 1.0; }" +
              "$_ = false;";
    Util.instrumentDescribed(thisClass, ctSkill, "alterSkill", desc4, "hasSleepBonus", replace);
    }