2

I wonder is it possible in Eclipse for Java (or rather in Java itself) to run a block of code only in debug mode? Just like in C++:

#ifdef DEBUG
  // something to do
#else
  // something else to do
#endif

I know there is no preprocessor in Java, but maybe there is some workaround?

rainbow
  • 1,161
  • 3
  • 14
  • 29

2 Answers2

2

I think the best way to approach this is to use a public static final boolean as a debug flag, import it when needed, and put your debug code in if blocks.

public static final boolean DEBUG = true;

import ClassName.DEBUG;

if (DEBUG) {
    doDebugThings();
}
MrPromethee
  • 721
  • 9
  • 18
  • 1
    But then I have to change something in code everytime when I want to debug. I thought rather about some Debug configuration...->Arguments value in Eclipse. – rainbow Jun 14 '17 at 08:06
  • You only need to have one configuration class in which you change the value. – MrPromethee Jun 14 '17 at 08:09
  • I just figured out an option. Debug confiiguration...->Environment gives to us a chance to set env vars. Then it would be possible to check such variable in app and even run it in debug-like mode. I have to check it... – rainbow Jun 14 '17 at 08:15
  • You have a flag in vm argument say myproject.DEBUG that you pass as argument to your program and in your startup code you initialize DEBUG using System.getProperty("myproject.DEBUG").equals("true") or Boolean.getProperty("myproject.DEBUG"). – Satish Jun 14 '17 at 08:18
  • @Satish Is it possible to read args[] via getProperty()? Anyway if you think about setting env arguments - I agree. Small disadvantage is Eclipse Run/Debug will always launch debug block. But I can live with it. – rainbow Jun 14 '17 at 08:43
  • 1
    @rainbow if you like pass it as one of the argument you can do I think like -Dmyproject.DEBUG=true – Satish Jun 14 '17 at 09:13
  • @MrPromethee Small correction: you've forgot about "static" after "import". – rainbow Jun 14 '17 at 09:46
0

there is no java way to do this, see Determine if a java application is in debug mode in Eclipse

there is this workaround: https://stackoverflow.com/a/43149241/5581745 that u could adapt to ur needs...

basic idea:

  1. use a conditional break point, e.g. a class loader break point on ur startup class
  2. write the condition like so MyDebug.setDebugModeOn();
    • in this method goes ur debug init code, e.g. where ur set a static public boolean DEBUG_MODE_IS_ON var.
    • always return false from this, so the break point never causes a stop
elonderin
  • 509
  • 4
  • 12