Search code examples
javamainclass

Java-Checking for main class


I had a problem in one of my java products, in which players would run a cheat class as the main class. Is there a way in which I can check for the main class running? I've tried adding a UID but they seemed to get past it.


Solution

  • This is hardly a robust and bulletproof solution, but you could try looking at the thread's stack trace and ensure that your class is the last element:

    final StackTraceElement[] stack = Thread.currentThread().getStackTrace();
    
    if (! stack[stack.length-1].getClassName().equals(YourClass.class.getName()))
    {
      // abort
    }
    

    However, there's nothing to stop someone compiling a class with the same fully qualified class name as your legitimate class and replacing your original one.