Search code examples
javajavascriptandroidprocessingmode

How to distinguish the mode (Java/JS/Android) the Processing sketch runs?


I write a multiplatform logic game, that will have to work in all modes: Java, JS and Android. I need to do some things different in all modes (especially, but not limited to, storage, for Java/Android I want to use load/saveTable and for JS - localStorage).

To do that I need to get the information, which is the mode the sketch runs. And I need to do this in runtime, just to avoid keeping different source for all platforms.

I was looking in the docs but found nothing in the topic. My Google research also led me to thoughts, that nobody even asked for that...

I was thinking about using try/catch to check some functions that exist in Java but not in JS, but this seems to be rather unelegant and whatismore I can not find the propper way for that.

What I have found is:

try {
  PApplet a;
  a = new PApplet();
  mode = "JAVA";
}
catch(Throwable e) {
  mode = "JS";
}

This distinguishes Java and JavaScript, but can not recognize Android...

So to summarize - what's the best way to distinguish, whether I run the sketch in JS or Java mode on runtime?


Solution

  • Ok, I have found quite nice way with try/catch:

    String mode;
    
    mode = "unknown";
    
    try {
      java.lang.Object a;
      a = new java.lang.Object();
      mode = "JAVA";
    }
      catch(Throwable e) {
      mode = "JS";
    }
    

    This distinguishes JavaScript from the Java/Android but can not distinguish Android from Java. But since the differences are minimal this not causes significant problems with compatibility to me.

    If someone knows the way to do this better - please post your answer!