Molehill
Molehill

Reputation: 35

Generating Java source code and jumps

I am generating Java code on the fly which will then be compiled and loaded back in. My issues is that I essentially need jumps because when I return from the function I wish to continue execution from the point in the loop from where I have exited. Hopefully, the code here illustrates my desire. Although the actual code will have some ifs as well and be much deeper.

MyIter a,b,c;

boolean func() {
 jump to correct state here

 state0:

 a = ...;
 while (a.next()) {
   state1: while (b.next()) {
     return true; // start again at state1
   }
   b = ...;
 }

 c = ...;
 state2:
 while (c.next()) {
   return true; // start again at state2
 }
 return false;
}

In C I would probably use a jump table and state variable. Performance is the key here and the code interacts with the Java application.

My best guesses so far have been:

I was wondering if anyone had any thoughts?

Upvotes: 0

Views: 537

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533500

The simplest option is to use a switch block (or if you have to, nested switch statements)

enum State {
   state1, state2, state3;
}

State state = State.state1;

public boolean func() {
   while(true) {
     switch(state) {
        case state1:
            if(test()) return true;
            state = state2;
            break;
        case state2:
            if(test2()) return false;
            state = state3;
            break;
        case state3:
            if(test3()) return true;
            state = state1;
            break;
      }
   }
}

Upvotes: 2

Brian Clapper
Brian Clapper

Reputation: 26211

A Java coroutine library might suit your purposes. See this related StackOverflow question for some pointers.

Upvotes: 0

Related Questions