Effective Java 35 Prefer annotations to naming patterns
Disadvantages of naming patterns
- Typographical errors may result in silent failures.
- There is no way to ensure that they are used only on appropriate program elements.
- They provide no good way to associate parameter values with program elements.
Naming patters example
testXXX
textXXXWithXXXException
Better solution: meta-annotations
// Marker annotation type declaration
import java.lang.annotation.*;
/**
* Indicates that the annotated method is a test method.
* Use only on parameter less static methods.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {
}
/**
* Indicates that the annotated method is a test method that must throw the
* designated exception to succeed.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ExceptionTest {
Class<? extends Exception> value();
}
/**
* Annotation type with an array parameter
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MultiExceptionTest {
Class<? extends Exception>[] value();
}
- The @Retention(RetentionPolicy.RUNTIME) meta-annotation indicates that Test annotations should be retained at runtime. Without it, Test annotations would be invisible to the test tool.
- The @Target(ElementType.METHOD)meta-annotation indicates that the Test annotation is legal only on method declarations: it cannot be applied to class declarations, field declarations, or other program elements.
- The parameter definition Class<? extends Exception> value(); and Class<? extends Exception>[] value(); declare the required one or more exceptions to be generated by the method.
// Program containing marker annotations
public class Sample {
@Test public static void m1() { } // Test should pass
public static void m2() { }
@Test public static void m3() { // Test Should fail
throw new RuntimeException("Boom");
}
public static void m4() { }
@Test public void m5() { } // INVALID USE: nonstatic method
public static void m6() { }
@Test public static void m7() { // Test should fail
throw new RuntimeException("Crash");
}
public static void m8() { }
}
/**
* @author Kaibo
* Program containing annotations with a parameter.
*/
public class Sample2 {
@ExceptionTest(ArithmeticException.class)
public static void m1() { // Test should pass
int i = 0;
i = i / i;
}
@ExceptionTest(ArithmeticException.class)
public static void m2() { // Should fail (wrong exception)
int[] a = new int[0];
int i = a[1];
}
@ExceptionTest(ArithmeticException.class)
public static void m3() {
} // Should fail (no exception)
}
/**
* @author Kaibo
*
*/
public class Sample3 {
// Code containing an annotation with an array parameter
@MultiExceptionTest({ IndexOutOfBoundsException.class,
NullPointerException.class })
public static void doublyBad() {
List<String> list = new ArrayList<String>();
// The spec permits this method to throw either
// IndexOutOfBoundsException or NullPointerException
list.addAll(5, null);
}
}
/**
* @author Kaibo
* Program to process marker annotations.
*/
import java.lang.reflect.*;
public class RunTests {
public static void main(String[] args) throws Exception {
Class<?> testClass = Class.forName(args[0]);
testSample1(testClass);
testClass = Class.forName(args[1]);
testSample2(testClass);
testClass = Class.forName(args[2]);
testSample3(testClass);
}
private static void testSample1(Class<?> testClass) {
int tests = 0;
int passed = 0;
for (Method m : testClass.getDeclaredMethods()) {
if (m.isAnnotationPresent(Test.class)) {
tests++;
try {
m.invoke(null);
passed++;
} catch (InvocationTargetException wrappedExc) {
Throwable exc = wrappedExc.getCause();
System.out.println(m + " failed: " + exc);
} catch (Exception exc) {
System.out.println("INVALID @Test: " + m);
}
}
}
System.out.printf("Passed: %d, Failed: %d%n", passed, tests - passed);
}
/**
* @param testClass
*/
private static void testSample2(Class<?> testClass) {
int tests = 0;
int passed = 0;
for (Method m : testClass.getDeclaredMethods()) {
if (m.isAnnotationPresent(ExceptionTest.class)) {
tests++;
try {
m.invoke(null);
System.out.printf("Test %s failed: no exception%n", m);
} catch (InvocationTargetException wrappedEx) {
Throwable exc = wrappedEx.getCause();
Class<? extends Exception> excType = m.getAnnotation(
ExceptionTest.class).value();
if (excType.isInstance(exc)) {
passed++;
} else {
System.out.printf(
"Test %s failed: expected %s, got %s%n", m,
excType.getName(), exc);
}
} catch (Exception exc) {
System.out.println("INVALID @Test: " + m);
}
}
}
System.out.printf("Passed: %d, Failed: %d%n", passed, tests - passed);
}
private static void testSample3(Class<?> testClass) {
int tests = 0;
int passed = 0;
for (Method m : testClass.getDeclaredMethods()) {
if (m.isAnnotationPresent(ExceptionTest.class)) {
tests++;
try {
m.invoke(null);
System.out.printf("Test %s failed: no exception%n", m);
} catch (Throwable wrappedExc) {
Throwable exc = wrappedExc.getCause();
Class<? extends Exception>[] excTypes = m.getAnnotation(
MultiExceptionTest.class).value();
int oldPassed = passed;
for (Class<? extends Exception> excType : excTypes) {
if (excType.isInstance(exc)) {
passed++;
break;
}
}
if (passed == oldPassed)
System.out.printf("Test %s failed: %s %n", m, exc);
}
}
}
System.out.printf("Passed: %d, Failed: %d%n", passed, tests - passed);
}
}
Summary
There is simply no reason to use naming patterns now that we have annotations. All programmers should, however, use the predefined annotation types provided by the Java platform(Item 36 and Item24).
Effective Java 35 Prefer annotations to naming patterns的更多相关文章
- Effective Java 69 Prefer concurrency utilities to wait and notify
Principle Use the higher-level concurrency utilities instead of wait and notify for easiness. Use Co ...
- Effective Java 53 Prefer interfaces to reflection
Disadvantage of reflection You lose all the benefits of compile-time type checking, including except ...
- Effective Java 68 Prefer executors and tasks to threads
Principle The general mechanism for executing tasks is the executor service. If you think in terms o ...
- Effective Java 18 Prefer interfaces to abstract classes
Feature Interface Abstract class Defining a type that permits multiple implementations Y Y Permitted ...
- Effective Java 20 Prefer class hierarchies to tagged classes
Disadvantage of tagged classes 1. Verbose (each instance has unnecessary irrelevant fields). 2. Erro ...
- Effective Java 25 Prefer lists to arrays
Difference Arrays Lists 1 Covariant Invariant 2 Reified at runtime Erased at run time 3 Runtime type ...
- Effective Java 46 Prefer for-each loops to traditional for loops
Prior to release 1.5, this was the preferred idiom for iterating over a collection: // No longer the ...
- Effective Java 49 Prefer primitive types to boxed primitives
No. Primitives Boxed Primitives 1 Have their own values Have identities distinct from their values 2 ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
随机推荐
- js关于对象键值为数字型时输出的对象自动排序问题的解决方法
一.对象键值为数字型时输出的对象自动排序问题如: var objs = { "1603":{id:"1603"}, "1702" ...
- Web 前端性能优化准则
准则01:尽量减少http请求 “只有10%-20%的最终用户响应时间花在接收请求的HTML文档上,剩下的80%-90%时间花在HTML文档所引用的所有组件(图片,script,css,flash等等 ...
- JS 跨域问题常见的五种解决方式
一.什么是跨域? 要理解跨域问题,就先理解好概念.跨域问题是由于javascript语言安全限制中的同源策略造成的. 简单来说,同源策略是指一段脚本只能读取来自同一来源的窗口和文档的属性,这里的同一来 ...
- MVC知识点01
1:母版页都 放在View/Shared里面,而且全部的视图页面都可以去用母板页. **母板的应用要用到嵌套,@RenderBody();将别的网页的内容全部显示在此处,它就相当于一个占位符. 2:架 ...
- win8.1安装开发工具vs2013.3+mssql2012全程
几个常用的命令 重起计算机命令:shoutdown.exe -r -t 0 立刻重起 在远程桌面中没有关机重起的选项,这个命令是必须的 远程桌面连接:mstsc 硬件环境:I7 4770 64RAM ...
- 迭代接口的IEnumerator
我们经常在工作中用到对List,Dictionary对象的Foreach遍历,取出每一项. 其实这个接口很简单,只有一个属性2个方法. [ComVisible(true), Guid("49 ...
- (一)JAVA项目(非web项目)部署到windows服务器运行
[转]http://blog.csdn.net/tracy19880727/article/details/11205063 一般服务器运行的几乎都是web项目,今天遇到一个问题,把写好的Java项目 ...
- C#一个方法返回多个值
示例代码: static void Main(string[] args) { //声明 int value; string strOutValue; //调用函数 //函数的参数有两个返回的值 Re ...
- Python记录-Pip安装
1.第一步 下载py文件:https://bootstrap.pypa.io/ez_setup.py #!/usr/bin/env python """ Setuptoo ...
- C# 快速反射 IL
public class FastInvoke { public delegate object FastInvokeHandler(object target, object[] paramters ...