Plantillas Útiles de Código Java de Eclipse [cerrado]


Puede crear varias plantillas de código Java en Eclipse a través de

Ventana > Preferencias > Java > Editor > Plantillas

Por ejemplo

sysout se expande a:

System.out.println(${word_selection}${});${cursor}

Puede activar esto escribiendo sysout seguido de CTRL+SPACE

¿Qué plantillas de código Java útiles utiliza actualmente?
Incluya el nombre y la descripción de la misma y por qué es impresionante.

Hay una recompensa abierta en esto por un uso original/novedoso de una plantilla en lugar de una incorporada característica existente.

  • Crear LOG4J logger
  • Obtener el color swt de la pantalla
  • Syncexec-Eclipse Framework
  • Patrón de Singleton / Enum Generación de Singleton
  • Readfile
  • Const
  • Traceout
  • Cadena de formato
  • Comentario Revisión del código
  • Formato de cadena
  • Intenta finalmente Bloquear
  • Formato de mensaje i18n y log
  • Equalsbuilder
  • Hashcodebuilder
  • Objeto de resorte Inyección
  • Crear FileOutputStream
Author: Jon, 2009-06-22

30 answers

Las siguientes plantillas de código crearán un registrador y crearán las importaciones correctas, si es necesario.

SLF4J

${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger LOG = LoggerFactory.getLogger(${enclosing_type}.class);

Log4J 2

${:import(org.apache.logging.log4j.LogManager,org.apache.logging.log4j.Logger)} 
private static final Logger LOG = LogManager.getLogger(${enclosing_type}.class); 

Log4J

${:import(org.apache.log4j.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);

Source .

JUL

${:import(java.util.logging.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class.getName());
 403
Author: Robert Munteanu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-23 14:03:28

Algunas plantillas adicionales aquí: Enlace I - Link II

Me gusta este:

Readfile

 ${:import(java.io.BufferedReader,  
           java.io.FileNotFoundException,  
           java.io.FileReader,  
           java.io.IOException)}  
 BufferedReader in = null;  
 try {  
    in = new BufferedReader(new FileReader(${fileName}));  
    String line;  
    while ((line = in.readLine()) != null) {  
       ${process}  
    }  
 }  
 catch (FileNotFoundException e) {  
    logger.error(e) ;  
 }  
 catch (IOException e) {  
    logger.error(e) ;  
 } finally {  
    if(in != null) in.close();  
 }  
 ${cursor} 

UPDATE : La versión Java 7 de esta plantilla es:

${:import(java.nio.file.Files,
          java.nio.file.Paths,
          java.nio.charset.Charset,
          java.io.IOException,
          java.io.BufferedReader)}
try (BufferedReader in = Files.newBufferedReader(Paths.get(${fileName:var(String)}),
                                                 Charset.forName("UTF-8"))) {
    String line = null;
    while ((line = in.readLine()) != null) {
        ${cursor}
    }
} catch (IOException e) {
    // ${todo}: handle exception
}
 47
Author: Jon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-30 08:47:59

Dar formato a una cadena

MessageFormat - rodea la selección con un MessageFormat.

 ${:import(java.text.MessageFormat)} 
 MessageFormat.format(${word_selection}, ${cursor})

Esto me permite mover un cursor a una cadena, expandir la selección a toda la cadena (Shift-Alt-Up), luego Ctrl-Espacio dos veces.

Bloquear la selección

Lock - rodea las líneas seleccionadas con un try finally lock. Supongamos la presencia de una variable de bloqueo.

${lock}.acquire();
try {
    ${line_selection}
    ${cursor}
} finally {
    ${lock}.release();
}

NB ${line_selection}las plantillas se muestran en el menú Envolvente Con (Alt-Shift-Z).

 31
Author: jamesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-23 22:24:32

Sé que estoy pateando un poste muerto, pero quería compartir esto por el bien de la finalización:

Una versión correcta de la plantilla de generación singleton, que supera el diseño de bloqueo doble comprobado defectuoso (discutido anteriormente y mencionado en otro lugar)

Plantilla de Creación de Singleton: Nombre esto createsingleton

static enum Singleton {
    INSTANCE;

    private static final ${enclosing_type} singleton = new ${enclosing_type}();

    public ${enclosing_type} getSingleton() {
        return singleton;
    }
}
${cursor}


Para acceder a singletons generados usando arriba:

Plantilla de referencia Singleton: Nombre esto getsingleton:

${type} ${newName} = ${type}.Singleton.INSTANCE.getSingleton();
 26
Author: questzen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-04 22:43:05

Para log, una pequeña cancioncilla útil para agregar en la variable miembro.

private static Log log = LogFactory.getLog(${enclosing_type}.class);
 25
Author: cgp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-22 19:03:57

Añade un fragmento de código para iterar sobre Map.entrySet():

Plantilla:

${:import(java.util.Map.Entry)}
for (Entry<${keyType:argType(map, 0)}, ${valueType:argType(map, 1)}> ${entry} : ${map:var(java.util.Map)}.entrySet())
{
    ${keyType} ${key} = ${entry}.getKey();
    ${valueType} ${value} = ${entry}.getValue();
    ${cursor}
}

Código generado:

for (Entry<String, String> entry : properties.entrySet())
{
    String key = entry.getKey();
    String value = entry.getValue();
    |
}

Pantallazo

 24
Author: mmdemirbas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-22 13:46:03

Crea un mock con Mockito (en el contexto "Java statements"):

${:importStatic('org.mockito.Mockito.mock')}${Type} ${mockName} = mock(${Type}.class);

Y en "Miembros de tipo Java":

${:import(org.mockito.Mock)}@Mock
${Type} ${mockName};

Simula un método void para lanzar una excepción:

${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}
doThrow(${RuntimeException}.class).when(${mock:localVar}).${mockedMethod}(${args});

Burlarse de un método vacío para hacer algo:

${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
    Object arg1 = invocation.getArguments()[0];
    return null;
}
}).when(${mock:localVar}).${mockedMethod}(${args});

Verificar método burlado llamado exactamente una vez:

${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.times)}
verify(${mock:localVar}, times(1)).${mockMethod}(${args});

Verificar que el método burlado nunca se invoca:

${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.never)}verify(${mock:localVar}, never()).${mockMethod}(${args});

Nueva lista enlazada usando Google Guava (y similar para hashset y hashmap):

${import:import(java.util.List,com.google.common.collect.Lists)}List<${T}> ${newName} = Lists.newLinkedList();

También utilizo una plantilla enorme que genera un Clase de prueba. Aquí hay un fragmento abreviado que todos los interesados deben personalizar:

package ${enclosing_package};

import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.junit.runner.RunWith;

// TODO autogenerated test stub
@RunWith(MockitoJUnitRunner.class)
public class ${primary_type_name} {

    @InjectMocks
    protected ${testedType} ${testedInstance};
    ${cursor}

    @Mock
    protected Logger logger;

    @Before
    public void setup() throws Exception {
    }

    @Test
    public void shouldXXX() throws Exception {
        // given

        // when
        // TODO autogenerated method stub

        // then
        fail("Not implemented.");
    }
}
// Here goes mockito+junit cheetsheet
 24
Author: mantrid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-22 10:13:30

Null Checks!

if( ${word_selection} != null ){
    ${cursor}
}

if( ${word_selection} == null ){
    ${cursor}
}
 23
Author: Prashant Bhate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-03 14:08:35

Uno de mis amados es foreach :

for (${iterable_type} ${iterable_element} : ${iterable}) {
    ${cursor}
}

Y traceout , ya que lo estoy usando mucho para rastrear:

System.out.println("${enclosing_type}.${enclosing_method}()");

Acabo de pensar en otro y lo he encontrado en Internet algún día, const :

private static final ${type} ${name} = new ${type} ${cursor};
 21
Author: Artem Barger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-03 14:07:24

Un pequeño consejo sobre sysout I Me gusta renombrarlo a "sop". Nada más en las libs de Java comienza con" sop "para que pueda escribir rápidamente" sop " y boom, se inserta.

 20
Author: Scott Stanchfield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-02 14:00:09

Lanza una excepción IllegalArgumentException con variable en el ámbito actual (illarg):

throw new IllegalArgumentException(${var});

Mejor

throw new IllegalArgumentException("Invalid ${var} " + ${var});  
 17
Author: javaguy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-05 20:10:55

Nada elegante para la producción de código, pero bastante útil para revisiones de código

Tengo mi plantilla coderev baja / med / alta hacer lo siguiente

/**
 * Code Review: Low Importance
 * 
 *
 * TODO: Insert problem with code here 
 *
 */

Y luego en la vista Tareas - me mostrará todos los comentarios de revisión de código que quiero traer durante una reunión.

 14
Author: PSU_Kardi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-01 21:41:20

Algunas plantillas más aquí.

Incluye:

  • Crear un objeto date a partir de una fecha en particular
  • Crear un nuevo ArrayList genérico
  • Configuración del registrador
  • Registro con el nivel especificado
  • Crear un nuevo HashMap genérico
  • Iterar a través de un mapa, imprimir las claves y valores
  • Analizar un tiempo usando SimpleDateFormat
  • Leer un archivo línea por línea
  • Registrar y repensar una excepción atrapada
  • Imprimir tiempo de ejecución de un bloque de código
  • Crear temporizador periódico
  • Escribir una cadena en un archivo
 14
Author: lrussell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-22 17:12:30

Slf4j Logging

${imp:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}

private static final Logger LOGGER = LoggerFactory
    .getLogger(${enclosing_type}.class);
 11
Author: Prashant Bhate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-12 02:18:04

Propiedad del frijol

private ${Type} ${property};

public ${Type} get${Property}() {
    return ${property};
}

public void set${Property}(${Type} ${property}) {
    ${propertyChangeSupport}.firePropertyChange("${property}", this.${property},     this.${property} = ${property});
}

PropertyChangeSupport

private PropertyChangeSupport ${propertyChangeSupport} = new PropertyChangeSupport(this);${:import(java.beans.PropertyChangeSupport,java.beans.PropertyChangeListener)}
public void addPropertyChangeListener(PropertyChangeListener listener) {
  ${propertyChangeSupport}.addPropertyChangeListener(listener);
}

public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
  ${propertyChangeSupport}.addPropertyChangeListener(propertyName, listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
  ${propertyChangeSupport}.removePropertyChangeListener(listener);
}

public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
  ${propertyChangeSupport}.removePropertyChangeListener(propertyName, listener);
}
 10
Author: qualidafial,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-29 23:20:43

Después de Java 7, una gran manera de configurar registradores que necesitan (o prefieren) referencias estáticas a la clase que encierra es usar la recientemente introducida MethodHandles API para obtener la clase de tiempo de ejecución en un contexto estático.

Un fragmento de código de ejemplo para SLF4J es:

private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

Además de ser un simple fragmento en cualquier IDE, también es menos frágil si refactoriza cierta funcionalidad en otra clase porque no llevará accidentalmente el nombre de la clase con ella.

 10
Author: Timothy055,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-30 08:50:38

Invocar código en el subproceso GUI

Enlazo la siguiente plantilla al atajo slater para enviar rápidamente el código en el subproceso GUI.

${:import(javax.swing.SwingUtilities)}
SwingUtilities.invokeLater(new Runnable() {      
      @Override
      public void run() {
        ${cursor}
      }
    });
 9
Author: Duncan Jones,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-13 09:27:44

Al probar con el código a veces me perdí la oportunidad de eliminar algunos syso s. Así que me hice una plantilla llamada syt.

System.out.println(${word_selection}${});//${todo}:remove${cursor}

Antes de compilar siempre compruebo mis TODOs y nunca olvidaré borrar un Sistema.fuera otra vez.

 9
Author: Calon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-22 06:18:37

strf -> String.format("msg", args) bastante simple, pero ahorra un poco de escritura.

String.format("${cursor}",)
 9
Author: pjp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-30 08:49:28

Obtenga un color SWT de la pantalla actual:

Display.getCurrent().getSystemColor(SWT.COLOR_${cursor})

Suround con syncexec

PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
    public void run(){
        ${line_selection}${cursor}
    }
});

Utilice el patrón de diseño singleton:

/**
 * The shared instance.
 */
private static ${enclosing_type} instance = new ${enclosing_type}();

/**
 * Private constructor.
 */
private ${enclosing_type}() {
    super();
}

/**
 * Returns this shared instance.
 *
 * @returns The shared instance
 */
public static ${enclosing_type} getInstance() {
    return instance;
}
 8
Author: Manuel Selva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-23 11:10:02

Y una adaptación de ecualsbuilder, hashcodebuilder:

${:import(org.apache.commons.lang.builder.EqualsBuilder,org.apache.commons.lang.builder.HashCodeBuilder)}
@Override
public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
}

@Override
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}
 8
Author: Jon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-25 00:03:05

La plantilla para la declaración del registrador es excelente.

También creo linfo, ldebug, lwarn, lerror para los niveles de registro que uso más a menudo.

Lerror:

logger.error(${word_selection}${});${cursor}
 8
Author: fgui,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-05 19:20:19

Crear todo para un evento

Dado que los eventos son un poco difíciles de crear en Java all todas esas interfaces, métodos y cosas para escribir solo para 1 evento I hice una plantilla simple para crear todo lo necesario para 1 evento.

${:import(java.util.List, java.util.LinkedList, java.util.EventListener, java.util.EventObject)}

private final List<${eventname}Listener> ${eventname}Listeners = new LinkedList<${eventname}Listener>();

public final void add${eventname}Listener(${eventname}Listener listener)
{
    synchronized(${eventname}Listeners) {
        ${eventname}Listeners.add(listener);
    }
}

public final void remove${eventname}Listener(${eventname}Listener listener)
{
    synchronized(${eventname}Listeners) {
        ${eventname}Listeners.remove(listener);
    }
}

private void raise${eventname}Event(${eventname}Args args)
{
    synchronized(${eventname}Listeners) {
        for(${eventname}Listener listener : ${eventname}Listeners)
            listener.on${eventname}(args);
    }
}

public interface ${eventname}Listener extends EventListener
{
    public void on${eventname}(${eventname}Args args);
}

public class ${eventname}Args extends EventObject
{
    public ${eventname}Args(Object source${cursor})
    {
        super(source);
    }
}

Si tiene eventos que comparten un único EventObject, simplemente elimine el personalizado insertado por la plantilla y cambie las partes apropiadas de raise___() y on____().

Había escrito un bonito, pequeño y elegante mecanismo de eventos usando una interfaz genérica y la clase genérica, pero no funcionaría debido a la forma en que Java maneja los genéricos. =(

Editar: 1) Me encontré con el problema donde los hilos estaban agregando / eliminando oyentes mientras se estaba llevando a cabo un evento. El List no se puede modificar mientras está en uso, por lo que agregué synchronized bloques donde se accede o se usa la lista de oyentes, bloqueando la lista en sí.

 8
Author: Benny Jobigan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-02 20:07:25

Insértese los métodos de ensayo should-given-when-then

Vi una versión similar a esta recientemente, mientras que el par de programación con un muy buen desarrollador y amigo, y creo que podría ser una buena adición a esta lista.

Esta plantilla creará un nuevo método de prueba en una clase, siguiendo el enfoque Dado - Cuando - Entonces del paradigma behavior-driven development (BDD) en los comentarios, como una guía para estructurar el código. Se iniciará el nombre del método con "debería" y le permitirá reemplazar el resto del nombre del método ficticio "Checkthisand That" con la mejor descripción posible de la responsabilidad del método de prueba. Después de llenar el nombre, la PESTAÑA le llevará directamente a // Given section, para que pueda comenzar a escribir sus precondiciones.

Lo tengo asignado a las tres letras "tst", con la descripción" Métodos de prueba deben-dado-cuando-entonces";)

Espero que lo encuentres tan útil como yo cuando lo vi:

@Test
public void should${CheckThisAndThat}() {
    Assert.fail("Not yet implemented");
    // Given
    ${cursor}

    // When


    // Then

}${:import(org.junit.Test, org.junit.Assert)}
 8
Author: MacLuq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-03 14:41:41

Inyección de resorte

Sé que esto es un poco tarde para el juego, pero aquí hay uno que uso para la inyección de primavera en una clase:

${:import(org.springframework.beans.factory.annotation.Autowired)}
private ${class_to_inject} ${var_name};

@Autowired
public void set${class_to_inject}(${class_to_inject} ${var_name}) {
  this.${var_name} = ${var_name};
}

public ${class_to_inject} get${class_to_inject}() {
  return this.${var_name};
}
 7
Author: Mike Clark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-18 19:45:50

Aquí hay un constructor para clases no instanciables:

// Suppress default constructor for noninstantiability
@SuppressWarnings("unused")
private ${enclosing_type}() {
    throw new AssertionError();
}

Este es para excepciones personalizadas:

/**
 * ${cursor}TODO Auto-generated Exception
 */
public class ${Name}Exception extends Exception {
    /**
     * TODO Auto-generated Default Serial Version UID
     */
    private static final long serialVersionUID = 1L;    

    /**
     * @see Exception#Exception()
     */
    public ${Name}Exception() {
        super();
    }

    /**
     * @see Exception#Exception(String) 
     */
    public ${Name}Exception(String message) {
        super(message);         
    }

    /**
     * @see Exception#Exception(Throwable)
     */
    public ${Name}Exception(Throwable cause) {
        super(cause);           
    }

    /**
     * @see Exception#Exception(String, Throwable)
     */
    public ${Name}Exception(String message, Throwable cause) {
        super(message, cause);
    }
}
 7
Author: David M. Coe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-10 14:14:28

Me gusta un comentario de clase generado como este:

/**
 * I... 
 * 
 * $Id$
 */

El " I..."inmediatamente anima al desarrollador a describir lo que hace la clase. Me parece mejorar el problema de las clases indocumentadas.

Y por supuesto $Id is es una palabra clave CVS útil.

 5
Author: skaffman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-01 21:49:49

He tenido mucho uso de estos fragmentos, buscando null valores y cadenas vacías.

Utilizo las plantillas "prueba de argumentos"como el primer código en mis métodos para comprobar los argumentos recibidos.

TestNullArgument

if (${varName} == null) {
    throw new NullPointerException(
        "Illegal argument. The argument cannot be null: ${varName}");
}

Es posible que desee cambiar el mensaje de excepción para que se ajuste al estándar de su empresa o proyecto. Sin embargo, recomiendo tener algún mensaje que incluya el nombre del argumento ofensivo. De lo contrario, la persona que llama de su método tendrá que mira en el código para entender lo que salió mal. (Un NullPointerException sin mensaje produce una excepción con el mensaje bastante absurdo "null").

TestNullOrEmptyStringArgument

if (${varName} == null) {
    throw new NullPointerException(
        "Illegal argument. The argument cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
    throw new IllegalArgumentException(
        "Illegal argument. The argument cannot be an empty string: ${varName}");
}

También puede reutilizar la plantilla de comprobación de null desde arriba e implementar este fragmento de código para verificar solo cadenas vacías. Entonces usarías esas dos plantillas para producir el código anterior.

La plantilla anterior, sin embargo, tiene el problema de que si el argumento in es final, tiene que modificar el código producido algunos (el ${varName} = ${varName}.trim() fallará).

Si utiliza muchos argumentos finales y desea comprobar si hay cadenas vacías, pero no tiene que recortarlas como parte de su código, podría ir con esto en su lugar:

if (${varName} == null) {
    throw new NullPointerException(
        "Illegal argument. The argument cannot be null: ${varName}");
}
if (${varName}.trim().isEmpty()) {
    throw new IllegalArgumentException(
        "Illegal argument. The argument cannot be an empty string: ${varName}");
}

TestNullFieldState

También he creado algunos fragmentos para comprobar variables que no se envían como argumentos (la gran diferencia es el tipo de excepción, ahora siendo un IllegalStateException en su lugar).

if (${varName} == null) {
    throw new IllegalStateException(
        "Illegal state. The variable or class field cannot be null: ${varName}");
}

TestNullOrEmptyStringFieldState

if (${varName} == null) {
    throw new IllegalStateException(
        "Illegal state. The variable or class field cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
    throw new IllegalStateException(
        "Illegal state. The variable or class field " +
            "cannot be an empty string: ${varName}");
}

TestArgument

Esta es una plantilla general para probar una variable. Me tomó unos años aprender a apreciar realmente este, ahora lo uso mucho (en combinación con las plantillas anteriores, por supuesto!)

if (!(${varName} ${testExpression})) {
    throw new IllegalArgumentException(
        "Illegal argument. The argument ${varName} (" + ${varName} + ") " +
        "did not pass the test: ${varName} ${testExpression}");
}

Se introduce un nombre de variable o una condición que devuelve un valor, seguido de un operando ("==", "" etc) y otro valor o variable y si la prueba falla el código resultante lanzará una excepción IllegalArgumentException.

La razón de la cláusula if ligeramente complicada, con toda la expresión envuelta en un "!() "es hacer posible reutilizar la condición de prueba en el mensaje de excepción.

Tal vez confundirá a un colega, pero solo si tiene que mirar el código, lo que podría no tener que hacer si lanzas este tipo de excepciones...

Aquí hay un ejemplo con matrices:

public void copy(String[] from, String[] to) {
    if (!(from.length == to.length)) {
        throw new IllegalArgumentException(
                "Illegal argument. The argument from.length (" +
                            from.length + ") " +
                "did not pass the test: from.length == to.length");
    }
}

Se obtiene este resultado por llamando a la plantilla, escribiendo " desde.length "[TAB] " = = to.longitud".

El resultado es mucho más divertido que un "ArrayIndexOutOfBoundsException" o similar y en realidad puede dar a sus usuarios la oportunidad de averiguar el problema.

Disfrute!

 5
Author: Erk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-31 17:54:25

Uso esto para MessageFormat (usando Java 1.4). De esa manera estoy seguro de que no tengo concatenaciones que sean difíciles de extraer al hacer internacionalización

I18n

String msg = "${message}";
Object[] params = {${params}};
MessageFormat.format(msg, params);

También para el registro:

Log

if(logger.isDebugEnabled()){
  String msg = "${message}"; //NLS-1
  Object[] params = {${params}};
  logger.debug(MessageFormat.format(msg, params));
}
 4
Author: Mario Ortegón,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-02 20:14:42

Mis favoritos son...

1: Javadoc, para insertar doc acerca de que el método es un método de inyección de objeto de resorte.

 Method to set the <code>I${enclosing_type}</code> implementation that this class will use.
* 
* @param ${enclosing_method_arguments}<code>I${enclosing_type}</code> instance 

2: Ventana de depuración, para crear un FileOutputStream y escribir el contenido del búfer en un archivo. Se usa para comparar un búfer con una ejecución anterior (usando BeyondCompare), o si no puedes ver el contenido de un búfer (a través de inspect) porque es demasiado grande...

java.io.FileOutputStream fos = new java.io.FileOutputStream( new java.io.File("c:\\x.x"));
fos.write(buffer.toString().getBytes());
fos.flush();
fos.close();
 4
Author: jeff porter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-03 08:31:52