`

Prefer annotations to naming patterns

阅读更多

    最近迷读Effective Java 2nd Edition,其中的ITEM 35: PREFER ANNOTATIONS TO NAMING PATTERNS,也就是用annotations来替代过去的使用名称模式的习惯,代码摆上:

 

// Annotation type with a parameter
import java.lang.annotation.*;

/**
 * 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();
}



// 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)
}



// Program to process marker annotations
import java.lang.reflect.*;

public class RunTests {
	public static void main(String[] args) throws Exception {
		int tests = 0;
		int passed = 0;
		Class<?> testClass = Class.forName("Sample2");
		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();
					// note the value is ArithmeticException.class
					// and test if the caused exception is the instance of the excType
					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);
	}
}

 

ExceptionTest是带参的annotation

测试类RunTests主要是测试Sample2类中哪个方法抛出通过annotation参数指定的异常,是则passed,否则failed

结果如下:

 

Test public static void Sample2.m2() failed: expected java.lang.ArithmeticException, got java.lang.ArrayIndexOutOfBoundsException: 1
Test public static void Sample2.m3() failed: no exception

Passed: 1, Failed: 2

分享到:
评论

相关推荐

    Effective Java 3rd edition(Effective Java第三版英文原版)附第二版

    Item 39: Prefer annotations to naming patterns Item 40: Consistently use the Override annotation Item 41: Use marker interfaces to define types 7 Lambdas and Streams Item 42: Prefer lambdas to ...

    专享:prefer的用法__(全).pdf

    13. “I would prefer to spend the weekend at home rather than driving all the way to your mother’s.”说话者宁愿在家度过周末,而不愿长途驾车去对方母亲家。 14. “I should prefer beef rather than ...

    新人教九年级英语unit单词讲解PPT课件.pptx

    4. **特定情况**:`prefer to do sth.` 用于强调在特定情境下,更愿意做某事,例如:"I prefer to walk."(我宁愿走路。) 5. **对比形式**:`prefer doing sth. to doing sth.` 这种结构表示在两个动作之间,更...

    Unit6 Good Manners语言点教案示例四 人教版.doc

    - "prefer doing A to doing B"或"prefer to do A rather than do B"都表示宁愿做A而不愿做B。例如:"I prefer working to sitting all day." 这里表达了更倾向于工作的态度。 - "prefer sb. to do sth."表示希望...

    动词后加to do 和 doing的记忆口诀[汇编].pdf

    此外,动词短语如begin to do、start to do、like to do、prefer to do、love to do、hate to do、forget to do、remember to do、stop to do、go on to do、try to do等,都用来表示动作的开始、继续或中断。...

    2020版九年级英语全册Unit4StoriesandpoemsLesson24WritingaPoem课件新版冀教版

    通过例句,如"I prefer red to green." 和 "The little boy prefers writing to singing.",来帮助学生理解"prefer"在不同语境下的使用。同时,提醒学生在使用"prefer...to..."结构时,前后动词的形式要一致,通常是...

    安徽省太和县北城中心学校九年级英语全册Unit9IlikemusicthatIcandancetoSectionA1a_2d导学

    3. prefer sth to sth,如:I prefer fish to meat. 或 I prefer reading to playing. 通过以上内容的学习,学生应能理解并运用这些词汇和语法结构,进行关于音乐喜好的交流,同时也能理解和使用定语从句,提升英语...

    介词to的用法归纳.pdf

    * prefer to * compare to * contrast to 这些例句中,to表示比较或对比的意思,强调两者之间的差异或相似性。 五、tҏ 与 及 个 别 的 名 词 构 成 比 较 之 意 在这个用法中,to与及个别的名词构成比较之意。...

    prefer.js:HTTP首选标头中间件

    var prefer = req.prefer; if (prefer.handling === 'strict') { // strict handling } else if (prefer.handling === 'lenient') { // lenient handling } if (prefer.respondAsync) { // client prefers ...

    Laravel开发-laravel-pdf-to-image

    composer create-project --prefer-dist laravel/laravel your_project_name ``` 接下来,你需要将 "laravel-pdf-to-image" 包添加到项目的 composer.json 文件中,然后运行 `composer install` 来安装依赖: ```...

    Berger_Goulding_Rice-Do small businesses still prefer community banks-JBF2014

    《Berger_Goulding_Rice-Do small businesses still prefer community banks-JBF2014》这篇研究论文探讨了在当前金融市场环境下,小型企业是否仍然倾向于选择社区银行作为主要金融服务提供商。本文将根据提供的标题...

    高中英语Unit3Traveljournalpart1WarmingupandPre_reading学案无答案新人教版必修1

    - I prefer to read books rather than listen to music. - I prefer doing reading rather than listening to music. - 优缺点分析:思考并列举各种交通方式的利弊,例如环保程度、速度、费用、舒适度等方面。 ...

    【上课用】非谓语考点:动词 固定非谓语to do.docx

    - "prefer to do" 表示更倾向于做某事,而 "prefer doing" 表示平时更喜欢做某事。 题目示例: 3. 题目"If he takes on this work, he will have no choice but ____________an even greater challenge.",这里使用...

    前端开源库-coffeelint-prefer-double-quotes

    `coffeelint-prefer-double-quotes` 是一个针对CoffeeScript语言的开源库,它旨在帮助开发者遵循特定的编码规范,特别是倾向于使用双引号的规则。CoffeeScript是一种简洁、富有表达力的JavaScript方言,它在语法上...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Naming General Naming Rules File Names Type Names Variable Names Constant Names Function Names Namespace Names Enumerator Names Macro Names Exceptions to Naming Rules Comments Comment Style File ...

    prefer-safe-http-header:Chrome扩展程序启用首选

    标题中的“prefer-safe-http-header”指的是一个Chrome浏览器的扩展程序,它的主要功能是启用“Prefer-Safe”HTTP头部。这个头部是一个提议的安全增强特性,用于向服务器表明客户端(这里是Chrome浏览器)更倾向于...

    I_would_prefer_not_to

    "I_would_prefer_not_to"这个标题可能暗示着某种不愿意或不情愿,但在HTML的世界里,我们可以理解为对特定技术或者实现方式的偏好。 首先,HTML的基本结构由一系列元素(tags)组成,这些元素通过尖括号包围,如`...

    Google C++ Style Guide_英文版.pdf

    - **Exceptions to Naming Rules:** There may be exceptions to these rules based on context or specific project requirements. #### Comments - **Comment Style:** Use clear and concise comments. Document...

    初中英语《Unit 9 I like music that I can dance to》导学案.pdf

    - **prefer doing to doing** 或 **prefer to do rather than do** 比起做...更喜欢做...。 2. **Australian** 是形容词,表示"澳大利亚的",对应的名词是 **Australian(s)**, "澳大利亚人"。 3. **electronic**...

    高考英语常用句型归纳整理.doc

    - **prefer to do sth rather than do sth**:表示在两个动作中选择前者,倾向于做某事而不是另一件事。 - **prefer doing sth to doing sth**:对比两个动作,更喜欢第一个。 - **prefer sth to sth**:在两个...

Global site tag (gtag.js) - Google Analytics