Jon*_*Jon 508 java eclipse ide templates code-generation
您可以通过Eclipse在Eclipse中创建各种Java代码模板
窗口>首选项> Java>编辑器>模板
例如
sysout 扩展到:
System.out.println(${word_selection}${});${cursor}
Run Code Online (Sandbox Code Playgroud)
您可以通过键入sysout后跟来激活它CTRL+SPACE
您目前使用哪些有用的Java代码模板?
包括它的名称和描述以及为什么它很棒.
对于原始/新颖的模板使用而不是内置的现有功能,这是一个开放的赏金.
Rob*_*anu 418
如果需要,以下代码模板将创建记录器并创建正确的导入.
SLF4J
${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger LOG = LoggerFactory.getLogger(${enclosing_type}.class);
Run Code Online (Sandbox Code Playgroud)
Log4J 2
${:import(org.apache.logging.log4j.LogManager,org.apache.logging.log4j.Logger)}
private static final Logger LOG = LogManager.getLogger(${enclosing_type}.class);
Run Code Online (Sandbox Code Playgroud)
Log4J的
${:import(org.apache.log4j.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);
Run Code Online (Sandbox Code Playgroud)
来源.
JUL
${:import(java.util.logging.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class.getName());
Run Code Online (Sandbox Code Playgroud)
Jon*_*Jon 48
我喜欢这一个:
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}
Run Code Online (Sandbox Code Playgroud)
更新:此模板的Java 7版本是:
${: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
}
Run Code Online (Sandbox Code Playgroud)
jam*_*esh 31
MessageFormat - 使用MessageFormat包围选择.
${:import(java.text.MessageFormat)}
MessageFormat.format(${word_selection}, ${cursor})
Run Code Online (Sandbox Code Playgroud)
这允许我将光标移动到一个字符串,将选择扩展到整个字符串(Shift-Alt-Up),然后将Ctrl-Space扩展两次.
锁定 - 使用try finally锁定所选行.假设存在锁变量.
${lock}.acquire();
try {
${line_selection}
${cursor}
} finally {
${lock}.release();
}
Run Code Online (Sandbox Code Playgroud)
NB ${line_selection}模板显示在Surround With菜单(Alt-Shift-Z)中.
que*_*zen 27
我知道我正在踢一个死的帖子,但是为了完成起见想分享这个:
正确版本的单件生成模板,克服了有缺陷的双重检查锁定设计(上面讨论并在其他地方提到)
单身人士创建模板:
将此命名createsingleton
static enum Singleton {
INSTANCE;
private static final ${enclosing_type} singleton = new ${enclosing_type}();
public ${enclosing_type} getSingleton() {
return singleton;
}
}
${cursor}
Run Code Online (Sandbox Code Playgroud)
要访问使用上面生成的单例:
单身人士参考模板:
将此命名为getsingleton:
${type} ${newName} = ${type}.Singleton.INSTANCE.getSingleton();
Run Code Online (Sandbox Code Playgroud)
mmd*_*bas 26
附加代码片段以迭代Map.entrySet():
${: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}
}
Run Code Online (Sandbox Code Playgroud)
for (Entry<String, String> entry : properties.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
|
}
Run Code Online (Sandbox Code Playgroud)

cgp*_*cgp 25
对于log,在成员变量中添加一个有用的小小调.
private static Log log = LogFactory.getLog(${enclosing_type}.class);
Run Code Online (Sandbox Code Playgroud)
man*_*rid 24
使用Mockito创建一个模拟(在"Java语句"上下文中):
${:importStatic('org.mockito.Mockito.mock')}${Type} ${mockName} = mock(${Type}.class);
Run Code Online (Sandbox Code Playgroud)
在"Java类型成员"中:
${:import(org.mockito.Mock)}@Mock
${Type} ${mockName};
Run Code Online (Sandbox Code Playgroud)
模拟一个void方法来抛出异常:
${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}
doThrow(${RuntimeException}.class).when(${mock:localVar}).${mockedMethod}(${args});
Run Code Online (Sandbox Code Playgroud)
模拟一个void方法来做某事:
${: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});
Run Code Online (Sandbox Code Playgroud)
验证一次调用的模拟方法:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.times)}
verify(${mock:localVar}, times(1)).${mockMethod}(${args});
Run Code Online (Sandbox Code Playgroud)
验证从不调用mocked方法:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.never)}verify(${mock:localVar}, never()).${mockMethod}(${args});
Run Code Online (Sandbox Code Playgroud)
使用Google Guava的新链接列表(以及类似的hashset和hashmap):
${import:import(java.util.List,com.google.common.collect.Lists)}List<${T}> ${newName} = Lists.newLinkedList();
Run Code Online (Sandbox Code Playgroud)
我还使用一个生成Test类的巨大模板.这是一个缩短的片段,每个人都应该自定义:
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
Run Code Online (Sandbox Code Playgroud)
Pra*_*ate 23
if( ${word_selection} != null ){
${cursor}
}
if( ${word_selection} == null ){
${cursor}
}
Run Code Online (Sandbox Code Playgroud)
Art*_*ger 21
我心爱的人之一是foreach:
for (${iterable_type} ${iterable_element} : ${iterable}) {
${cursor}
}
Run Code Online (Sandbox Code Playgroud)
并且跟踪,因为我正在使用它进行跟踪:
System.out.println("${enclosing_type}.${enclosing_method}()");
Run Code Online (Sandbox Code Playgroud)
我只想到另一个,并且有一天在互联网上找到它,const:
private static final ${type} ${name} = new ${type} ${cursor};
Run Code Online (Sandbox Code Playgroud)
Sco*_*eld 20
关于sysout的一点建议 - 我喜欢将其重命名为"sop".java libs中没有任何其他内容以"sop"开头,因此您可以快速输入"sop"和boom,它会插入.
Jon*_*Jon 17
使用当前范围(illarg)中的变量抛出IllegalArgumentException:
throw new IllegalArgumentException(${var});
Run Code Online (Sandbox Code Playgroud)
更好
throw new IllegalArgumentException("Invalid ${var} " + ${var});
Run Code Online (Sandbox Code Playgroud)
PSU*_*rdi 14
没有什么花哨的代码生成 - 但对代码审查非常有用
我有我的模板coderev low/med/high执行以下操作
/**
* Code Review: Low Importance
*
*
* TODO: Insert problem with code here
*
*/
Run Code Online (Sandbox Code Playgroud)
然后在Tasks视图中 - 将显示我想要在会议期间提出的所有代码审查注释.
Pra*_*ate 11
${imp:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger LOGGER = LoggerFactory
.getLogger(${enclosing_type}.class);
Run Code Online (Sandbox Code Playgroud)
qua*_*ial 10
豆财产
private ${Type} ${property};
public ${Type} get${Property}() {
return ${property};
}
public void set${Property}(${Type} ${property}) {
${propertyChangeSupport}.firePropertyChange("${property}", this.${property}, this.${property} = ${property});
}
Run Code Online (Sandbox Code Playgroud)
的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);
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*055 10
在Java 7之后,设置需要(或更喜欢)对封闭类的静态引用的记录器的一种好方法是使用新引入的MethodHandles API在静态上下文中获取运行时类.
SLF4J的示例代码段是:
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
Run Code Online (Sandbox Code Playgroud)
除了作为任何IDE中的简单片段之外,如果您将某些功能重构到另一个类中,它也不会那么脆弱,因为您不会意外地携带类名.
strf -> String.format("msg", args) 非常简单,但节省了一点打字.
String.format("${cursor}",)
Run Code Online (Sandbox Code Playgroud)
在GUI线程上调用代码
我将以下模板绑定到快捷方式,slater以便在GUI线程上快速分派代码.
${:import(javax.swing.SwingUtilities)}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
${cursor}
}
});
Run Code Online (Sandbox Code Playgroud)
在使用代码进行测试时,我有时会错过删除一些syso.所以我自己做了一个名为syt的模板.
System.out.println(${word_selection}${});//${todo}:remove${cursor}
Run Code Online (Sandbox Code Playgroud)
在编译之前,我总是检查我的TODO,并且永远不会忘记再次删除System.out.
从当前显示中获取SWT颜色:
Display.getCurrent().getSystemColor(SWT.COLOR_${cursor})
Run Code Online (Sandbox Code Playgroud)
与syncexec共存
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
public void run(){
${line_selection}${cursor}
}
});
Run Code Online (Sandbox Code Playgroud)
使用单例设计模式:
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
和一个equalsbuilder,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);
}
Run Code Online (Sandbox Code Playgroud)
记录器声明的模板非常棒.
我还为我经常使用的日志级别创建linfo,ldebug,lwarn,lerror.
lerror:
logger.error(${word_selection}${});${cursor}
Run Code Online (Sandbox Code Playgroud)
由于在Java中创建事件有点痛苦 - 所有这些接口,方法和仅为1个事件编写的东西 - 我创建了一个简单的模板来创建1个事件所需的所有内容.
${: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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您有共享一个单一的事件EventObject,只是删除定制一个由模板插入和修改的适当部位raise___()和on____().
我使用通用接口和泛型类编写了一个漂亮,小巧,优雅的事件机制,但由于Java处理泛型的方式,它不起作用.=(
编辑:1)我遇到了线程在事件发生时添加/删除侦听器的问题.在List不能在使用时进行修改,所以我加入synchronized其中侦听器列表被访问或使用的块,锁定列表本身上.
我最近看到了与这个版本类似的版本,但是与一个非常优秀的开发人员和朋友进行了对编程,我认为这可能是这个列表的一个很好的补充.
该模板将在类上创建一个新的测试方法,遵循来自行为驱动开发(BDD)范例的Given-When-Then方法,作为构造代码的指南.它将使用"should"启动方法名称,并允许您使用测试方法职责的最佳描述替换其余的虚拟方法名称"CheckThisAndThat".在填写名称后,TAB将直接带您到,因此您可以开始输入您的前提条件.// Given section
我将它映射到三个字母"tst",其描述为"测试方法应当给予时 - 然后";)
我希望你发现它和我看到它时一样有用:
@Test
public void should${CheckThisAndThat}() {
Assert.fail("Not yet implemented");
// Given
${cursor}
// When
// Then
}${:import(org.junit.Test, org.junit.Assert)}
Run Code Online (Sandbox Code Playgroud)
弹簧注射
我知道这对游戏来说有点晚了,但这里有一个我在一个类中用于Spring Injection的方法:
${: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};
}
Run Code Online (Sandbox Code Playgroud)
这是非实例化类的构造函数:
// Suppress default constructor for noninstantiability
@SuppressWarnings("unused")
private ${enclosing_type}() {
throw new AssertionError();
}
Run Code Online (Sandbox Code Playgroud)
这个用于自定义例外:
/**
* ${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);
}
}
Run Code Online (Sandbox Code Playgroud)
我喜欢这样生成的类注释:
/**
* I...
*
* $Id$
*/
Run Code Online (Sandbox Code Playgroud)
"我......"立即鼓励开发人员描述该课程的作用.我似乎确实改善了未记录的类的问题.
当然$ Id $是一个有用的CVS关键字.
我已经使用了很多这些片段,寻找null值和空字符串.
我使用"参数测试"-templates作为我的方法中的第一个检查接收参数的代码.
testNullArgument
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
Run Code Online (Sandbox Code Playgroud)
您可能希望更改异常消息以符合您公司或项目的标准.但是,我建议使用包含违规参数名称的消息.否则,您的方法的调用者将不得不查看代码以了解出错的地方.(NullPointerException没有消息的A 会产生一个带有相当荒谬的消息"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}");
}
Run Code Online (Sandbox Code Playgroud)
您还可以重用上面的空检查模板,并实现此片段以仅检查空字符串.然后,您将使用这两个模板来生成上述代码.
但是,上面的模板有一个问题,即如果in参数是final,你将不得不修改生成的代码(${varName} = ${varName}.trim()将失败).
如果你使用了很多最终参数并想要检查空字符串但不必将它们作为代码的一部分进行修剪,那么你可以改为:
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}");
}
Run Code Online (Sandbox Code Playgroud)
testNullFieldState
我还创建了一些片段来检查未作为参数发送的变量(最大的区别是异常类型,现在是异常IllegalStateException).
if (${varName} == null) {
throw new IllegalStateException(
"Illegal state. The variable or class field cannot be null: ${varName}");
}
Run Code Online (Sandbox Code Playgroud)
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}");
}
Run Code Online (Sandbox Code Playgroud)
testArgument
这是测试变量的通用模板.我花了几年才真正学会欣赏这个,现在我经常使用它(当然结合上面的模板!)
if (!(${varName} ${testExpression})) {
throw new IllegalArgumentException(
"Illegal argument. The argument ${varName} (" + ${varName} + ") " +
"did not pass the test: ${varName} ${testExpression}");
}
Run Code Online (Sandbox Code Playgroud)
输入变量名称或返回值的条件,后跟操作数("==","<",">"等)和另一个值或变量,如果测试失败,结果代码将抛出IllegalArgumentException.
稍微复杂的if子句的原因是整个表达式包含在"!()"中,这使得可以在异常消息中重用测试条件.
也许它会让同事感到困惑,但前提是他们必须查看代码,如果你抛出这些异常,他们可能不需要这样做......
这是一个数组示例:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
通过调用模板,输入"from.length"[TAB]"== to.length"得到这个结果.
结果比"ArrayIndexOutOfBoundsException"或类似的方式更有趣,实际上可能会让您的用户有机会找出问题所在.
请享用!