"Effective Java 2nd Edition" Maruzen Publishing
Annotation (English: annotation) is to add related information (metadata) to a certain data as an annotation.
[Annotation-Wikipedia](https://ja.wikipedia.org/wiki/%E3%82%A2%E3%83%8E%E3%83%86%E3%83%BC%E3%82%B7% E3% 83% A7% E3% 83% B3) Quote
Introduced from Java 5 (released in 2004)
CalculationTest.java
public class CalculationTest {
/**Test case 1*/
@Test
public void sampleTest1() {
//...
}
/**Test case 2*/
@Test
public void sampleTest2() {
//...
}
}
@Test
@Test
CalculationTest.java
public class CalculationTest extends TestCase{
/**Test case 1*/
public void testSample1() {
//...
}
/**Test case 2*/
public void testSample2() {
//...
}
}
Indicates that it is a test class by inheriting TestCase
Method names that become test cases start with test
⇒ Naming pattern
Http://d.hatena.ne.jp/smada564/20110501/1304265351 Reference
tsetSample2
(typo), it just won't be executed. No errorFor example, consider a test method that expects to throw ʻIllegalArgumentException`.
/**How to write JUnit4*/
@Test(expected = IllegalArgumentException.class)
public void sample() {
//...
}
/**Example when annotation cannot be used*/
public void test_IllegalArgumentException_sample() {
//...
}
Ugly and vulnerable
Compile cannot determine if an Exception exists --I don't notice until I run it
"Effective Java 2nd Edition" Item 35 Reference
Servlet can be set with either annotation or XML.
@WebServlet("/Hello")
public class HelloServlet extends HttpServlet {
//...
}
web.xml
<!--If not use annotation, specify in XML-->
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>jp.co.sample.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
Annotation features compared to XML
⇒ ** Strong against source changes **
@Override
Annotation indicating that the method is overridden.
Book.java
public class Book {
public Book(String title, String author) {
this.title = title;
this.author = author;
}
String title;
String author;
@Override //Compile Error.Correctly equals(Object obj)
public boolean equals(Book obj) {
//Null check omitted
return title.equals(obj.title) && author.equals(obj.author);
}
}
At compile time, notice that it is not overriding (overloaded).
@Deprecated
From Java9, you can write @Deprecated (since =" 9 ", forRemoval = true)
.
Is it going to be abolished? (forRemoval)
When will it be abolished? (since)
What ’s New for Core Libraries in JDK Reference
@SuppressWarnings
Make the IDE suppress warning messages.
@SuppressWarnings( "unchecked" ) //Exclude warnings about type checking
@SuppressWarnings( "javadoc" ) //JavaDoc warning exclusion
public class Book {
//..
}
http://www.oracle.com/webfolder/technetwork/jp/javamagazine/Java-MA14-Architect-TypeAnnotations.pdf http://www.oracle.com/webfolder/technetwork/jp/javamagazine/Java-MA16-Annotations.pdf
Recommended Posts