Niko P
Niko P

Reputation: 41

Executing a piece of bytecode

Think about this sample code:

...
try {
    stm1
    stm2
    stm3
} catch(){
    ...
}
...

Suppose to run the code and within the try block an exception is raised. Execution flow goes into the catch block.

Here, I would like to copy the bytecode of the try block (maybe using ASM), apply some modifications to the bytecode (for example substitute stm2 with stm4) and execute the new piece of bytecode within the catch block.

Is this possible without compiling or loading the new bytecode, but just executing it like an interpreted language?

Thank you!

UPDATE

I know that I can write the right piece of code a priori. The question is not why, but how to do that and if it is possible.

Suppose that I have to compute the new try body dynamically and that I have to execute the new code within the same object (because of the local variables and class variables.)

Upvotes: 2

Views: 311

Answers (4)

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

You can decompose those individual statements into separate methods or classes and use Java reflection to call individual statements. Then it is up to you in what order you'd iterate trough those reflective calls.

Another option would be generating piece of code dynamically and execute it using one of the scripting languages supported for JVM, such as BeanShell, Groovy, JavaScript/Rhino, etc.

Upvotes: 0

TMN
TMN

Reputation: 3070

You'd probably be better off setting up a state machine and dynamically determining the next state. Something like:

int nextState = 0;
while(nextState != -1) {
    try {
        switch(nextState) {
            case 0:
                stm1;
                ++nextState;
                break;
             case 1:
                stm2;
                ++nextState;
                break;
             case 2:
                stm3;
                nextState = -1;
                break;
             case 3:
                stm4;
                nextState = 2;
                break;
        }
    } catch (Exception err) {
        nextState = 3;
    }
}

Upvotes: 1

user425367
user425367

Reputation:

Not bytecode solution but Java :)

Maybe you can solve the problem by just typing the logic in the catch statement. One drawback will be that try catch block will be nested inside each and it will look ugly.

But it think it will be more maintainable that byte code loading.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

The following is by far the simplest

try {
    stm1
    stm2
    stm3
} catch(){
    stm1
    stm4 // instead of stm2
    stm3
}

You can do what you suggest with ASM also. However, almost any alternative approach you take is likely to be simpler. ASM is usually the best option when you have little control over the code you are running (or rarely for performance) I would assume you have some control over the code.

Upvotes: 0

Related Questions