简体   繁体   中英

Eclipse code templates

I'm attempting to edit the code template for class body in Eclipse. The desired end result would be that I press the shortcut key to trigger a new class being created with the following code already in place. Class name in place of ${enclosing_type} and the cursor where ${cursor} is placed.

import java.util.Scanner;

public class ${enclosing_type} {

    public static void main(String[] args) {
        Scanner ina = new Scanner(System.in);
        ${cursor}

    }
}

When editing this template I get the following error messages. Variable 'enclosing_type' is unknown. Variable 'cursor' is unknown. I've seen these mentioned in plenty of places. What am I missing?

Code templates and editor templates are two different things in eclipse, even though they look similar on first glance. With the code template for a class type body you define what is generated into the new class before the editor actually opens (and before any context is available for that new piece of code). Therefore code templates do not have a cursor variable, as it doesn't make sense for just generating the code.

And the class body template itself only applies to the inner code part between the class name and the closing brace, therefore it also doesn't resolve any enclosing type variable.

In contrast to code templates the editor templates are processed in the context of an already opened editor, with a semantic model available. Therefore many more variables are available there.

To not get confused in the future, you should insert template variables always by means of the button inside the template editor, not by manually writing. That way you always see which template variables are valid in that template editor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM