Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Is there support for macros?

I am just curious on how people solve this. I often write the same type of code all the time. For instance:

new Thread() {
   //...
   //...
   //...
   //Change this line
   //...
   //...
}.start();

I keep changing the line where it says "Change this line" and then starting a thread. This change can be one line or a few lines. How would I go about compacting this code?

like image 277
Legend Avatar asked Nov 13 '09 22:11

Legend


People also ask

What is macros in Java?

These macros handle text formatting and generation tasks that are particularly useful in writing Java code. Create_Constructor.bsh. Inserts constructor for the class at the current caret position.

Can I use #define in Java?

Java doesn't have a general purpose define preprocessor directive. private static final int PROTEINS = 100; Such declarations would be inlined by the compilers (if the value is a compile-time constant).

Does Java have preprocessor?

Java implementation does not have a preprocessor.

Are there macros in Python?

You can write an Excel macro in python to do whatever you would previously have used VBA for. Macros work in a very similar way to worksheet functions. To register a function as a macro you use the xl_macro decorator. Macros are useful as they can be called when GUI elements (buttons, checkboxes etc.)


Video Answer


2 Answers

Well, I guess you could run your java files through the C preprocessor...

like image 192
gnud Avatar answered Sep 17 '22 12:09

gnud


You can use the template pattern to create a base class that contains the common code. For example:

public abstract class ThreadTemplate extends Thread
{

    public void run() {
        //reusable stuff
        doInThread();
        //more resusable stuff
    }

    abstract void doInThread();

}

Then starting a thread with the boilerplate code is as easy as:

new ThreadTemplate{
   void doInThread() {
       // do something
   }
}.start();

Also, a less elegant solution to save yourself some typing is to use the templating feature of your ide. You can find some info on setting them up in Eclipse here and you can find a list of useful ones at Useful Eclipse Java Code Templates

like image 35
Jason Gritman Avatar answered Sep 17 '22 12:09

Jason Gritman