Embed #ifdef in Java

I have an algorithm written in C and it has code that can be processed by the C preprocessor, but since there is no preprocessor in java, I don’t know how to write Java code to handle such a thing. Code C

#ifdef Tile_size_utility #define print_error 0 else #define print_error 1 #endif 

How can I implement this in Java?

+4
source share
5 answers
  Class ErrorVerbose { private static boolean enabled = False; public static setEnable(boolean enable) enabled = enable; } public static perror(String msg) { if (enabled) { /* Print */ } } } class YourClass { public YourClass(....,boolean status) { ErrorVerbose.SetEnable(status) . . } } 

Well, yes, or you can do it, it's not a static class so other classes can enable / disable verbose ones. The advantage of creating the ErrorVerbose class is that you add additional information such as time, date, function name (which is called), etc., which makes it more informative, I just gave the skeleton.

+1
source

We cannot translate it to Java. We need to analyze where the property ( Tile_size_utility ) is set and where we need print_error . Then we can implement an equivalent solution.

Example: it is assumed that Tile_size_utility is a system property (set in the environment), and we need print_error as a (logical) flag, then this should work:

 public class MyClass { public final static boolean PRINT_ERROR = (System.getProperty("Tile_size_utility") != null); } 

Now, if you do a few set Tile_size_utility=myutiliy or run java with argument

 -DTile_size_utility=myutiliy 

then print_error will be set to true .

+3
source

You can not.

But Java has inheritance and polymorphism. You can use these concepts along with a dependency injection pattern to solve the problem cleaner, but in a different way.

I can give you a more accurate answer if you post data on what this print_error is doing.

+1
source

Create DefineManger using:

 abstract public class DefineManager { abstract public boolean isDefined(String k); abstract public String getDefine(String k); abstract public void setDefine(String k, String v); abstract public void undefine(String k); } if (isDefined("Tile_size_utility")) { setDefine("print_error", "0"); } else { setDefine("print_error", "1"); } 
0
source

The JVM automatically compiles the code in native so that these parameters can be changed at runtime to get the same performance.

You will probably find that many of the tricks supported by C ++ are not needed in Java, as it has other solutions to the problem that remain in the JVM. Java, as a rule, works poorly in comparison with other languages, but what it has is strongly optimized in such a way that may surprise some developers.

0
source

Source: https://habr.com/ru/post/1401736/


All Articles