How to automatically insert class notation using eclipse templates?

Does anyone know how to insert "@RunWith anotation" over a class signature using eclipse templates?

Example:.

@RunWith(Parameterized.class) public class MyClassTest { ... @Parameters public static Collection<Object[]> parameters() { List<Object[]> list = new ArrayList<Object[]>(); list.add(new Object[] { "mind!", "find!" }); list.add(new Object[] { "misunderstood", "understood" }); return list; } ... } 

__

Template:

 // TODO: move this '@RunWith(Parameterized.class)' to class anotation @Parameters public static Collection<Object[]> parameters() { ${type:elemType(collection)}<Object[]> parametersList = new ${type:elemType(collection)}<Object[]>(); ${cursor}// TODO: populate collection return parametersList; } 

__ Thanks for the help!

+4
source share
1 answer

Unfortunately, you cannot use Eclipse templates to add annotation to an existing surrounding class (at least I don't know). However, there is a workaround. Here is a modified version of your template:

 @${runnerType:newType(org.junit.runner.RunWith)}(${paramterizedType:newType(org.junit.runners.Parameterized)}.class) public class ${primary_type_name} { @${parametersType:newType(org.junit.runners.Parameterized.Parameters)} public static ${collectionType:newType(java.util.Collection)}<Object[]> parameters() { ${baseCollectionType}<Object[]> parametersList = new ${concreteCollectionType}<Object[]>(); ${cursor}// TODO: populate collection return parametersList; } } 

To use a template (assuming its name is "Parameterized"):

  • Create a new class in Eclipse
  • Before you do anything else, select the declaration of the stub class, including the opening and closing curly braces.
  • Enter the name of the template and press Cntrl+Space to activate the template (you may need to select a template from the list of templates. I only have one template with parameters, so Eclipse just uses it automatically for me).

The class definition will be replaced by a definition that includes the @RunWith annotation. I used the template variable $ {id: newName (reference)} to force Eclipse to automatically add all the necessary imports (except for imports for ${baseCollectionType} and ${concreteCollectionType} , you'll have to add them manually ... thanks for the kindness of Cntrl-Shift-M )

It is very difficult to describe. You need to try to see how it works. Post a comment if my instructions need to be clarified.

+3
source

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


All Articles