Categories
Uncategorized

NOTE Using java summary

In 2005, sun launched a jdk1.5, while the launch of the annotation features to attract the attention of many people, using annotations to code, java programmers can alleviate the suffering of the tedious configuration.

Use annotations can write easier to maintain, bug less code.

What comment is it? According to the official statement, notes that meta tags can be added to your code, and applied to package declarations, type declarations, constructors, methods, fields, parameters and variables.

Notes provides a very useful way to show whether the method you write that rely on other methods, whether they are complete, whether to write the class refer to other classes, and so on.

According to Oracle’s official statement, based on notes written in the java code template code is generated based on the source code comments, so we avoid writing boilerplate code in most cases. This leads to a declarative programming style, in this style, the programmer says what to do, the utility will write the appropriate code to implement it.

Briefly, the annotation is a mechanism for meta tags associated with the program element, and allows the virtual machine compiler or extracted from the annotation program behavior elements, and generate the code interdependent when necessary.

Now for our java annotations learning journey.

Built-in notes
    java will be built some of which have achieved good notes, you can directly use the built-in annotation is mainly used to provide java compiler directive.

There are five built-in java annotations:

  • @Deprecated
  • @Override
  • @SuppressWarnings
  • @SafeVarargs
  • @FunctionalInterface

@Deprecated mainly used to annotate classes, methods, variables marked with labels is not recommended to use, if you use the code does not recommend the use of classes, methods, variables, the compiler will give you a warning.
    The following are examples of the use @Deprecated:

public class AnnotationTest {
    public static void main(String args[]){
        MyAnnotation myAnnotation = new MyAnnotation();
        int age = myAnnotation.age;
        myAnnotation.eat();
    }
}

@Deprecated 
class MyAnnotation {
    @Deprecated
    int age;
    
    @Deprecated
    void eat(){
        
    }
}

Defines a MyAnnotation, are used on the class name, variable and method names @Deprecated comment.

When using the identification @Deprecated classes, methods, or variables,

@Deprecated there is another use, javadoc is stated in the document class, method or variable Why is not recommended, and alternative methods are given:

@Deprecated
/**
  @deprecated 已废弃,请使用MyNewComponent.
*/
class MyComponent {

}

@Override annotations on the method used, the identity of the parent class override this method. If this method is inconsistent, and the parent class method, the compiler will display an error.

It is strongly recommended to use the method in the parent class @Override rewriting notes, do not have any effect, but if you do not use @Override comment when someone changes the method of the parent class, you will not be able to identify whether the sub-category method rewrite the parent class. The use of @Override notes, as long as the parent does not have this method, the compiler will prompt an error does not correspond to the parent class method.
    Here is an example using @Override annotation:

class Anaimal{
    public void run(){
        
    }
}

class Cat extends Anaimal{
    @Override
    public void run(){
        
    }
}

RUN Cat class () method uses @Override annotations, if the method to runl Cat class (), the compiler is displayed The method run1 of type Cat must override or implement a supertype error ().

If no @Override annotation, a method to runl Cat class (), the system is not being given.

When @SuppressWarnings comment also on the method for suppressing warnings of deprecated method call or by type of conversion unsafe, the compiler will issue some warnings, use @SuppressWarnings you can ignore those warnings.
    Example of use:

@SuppressWarnings
public void methodWithWarning() {


}

@SafeVarargs annotation is mainly used for suppression parameter type safety warning, this is jdk1.7 new features.
    Example of use:

@SafeVarargs
static void testSafeVarargs(List ... stringLists) {
    Object[] array = stringLists;
    List tmpList = Arrays.asList(42);
    array[0] = tmpList; 
    String s = stringLists[0].get(0);
}

If you do not use @SafeVarargs annotation, the compiler will give a warning: Type safety: Potential heap pollution via varargs parameter stringLists.
    Use @SafeVarargs there is a premise, you must ensure that the use of a variable length parameter method, the type of security problem does not occur when used with generic classes. Otherwise running row will throw a ClassCastException.

@SafeVarargs annotations only on the method satisfies the following conditions:

    Variable-length method or constructor parameter.

    The method must be declared as static or final.

@FunctionalInterface annotation is mainly used to compile the level of error checking, with the comment, when you write the interface does not meet the functional interface definition, the compiler will complain.
    Example of use:

@FunctionalInterface
interface GreetingService
{
    void readMessage(String message);
}

Creating notes
    Annotations and create an interface somewhat similar, are using the word customs seized interface, except that when you create a comment, you need to add a @ character in front of the interface.

Here is an example to create a comment:

public @interface MyAnnotation {
}

Creating top notes do not have any member variables.

Create notes with a member variable:

@interface TestAnnotation{
    int age();
    String name();
}

TestAnnotation annotation has two member variables, age and name.
    Annotated member variable declarations in a non-parametric method no method body form.

Use the default keyword specifies the default value annotation member variable:

@interface TestAnnotation{
    int age() default  2;
    String name() default  “小明”;
}

When using custom annotations, annotation if the variable has a default value, you can not specify a value for the member variable, direct use of default values.
    Example of use:

@interface TestAnnotation{
    int age() default 2;
    String name() default "小明";
}


class MyAnnotation {
    @TestAnnotation
    public void getInfo(){
        
    }
}

If the variable comment no default, you must specify values ​​for each variable in the use of all, the code is as follows:

@interface TestAnnotation{
    int age();
    String name();
}


class MyAnnotation {
    @TestAnnotation(age=2,name="小明")
    public void getInfo(){
        
    }
}

Yuan notes
    What is a meta-annotation it? Annotation is the annotation metadata annotations, annotation is used to define the annotation, the annotation can be understood as basic data types. This stuff is really hard to pronounce, or look at the code more comfortable.

@Target(ElementType.METHOD)
@interface Test_Target {
   public String doTestTarget();
}

@Target meta-annotation is used to define Test_Target comment.

java provides five yuan notes, are:

    @Retention specify annotations life cycle, namely survival time.

    Documents @Documented javadoc command generated reflect the content of the comment

    @Target specified annotation element which may be used, such as classes, methods, variables,

    @Inherited inheritance annotations,

    Notes @Repeatable reusable

@Retention annotation is used to specify the life cycle, namely survival time. @Retention provides the following three values, @Retention in use, which must be of a value.

    RetentionPolicy.SOURCE comment only remain in the source stage, discarded when compiling the generated class file compiler, annotation information can not be obtained through reflection.

    RetentionPolicy.CLASS notes are only kept to be compiled when it will not be loaded into the JVM, annotation information can not be obtained by reflection, which is the default.

    RetentionPolicy.RUNTIME annotation can be retained when the program is running, it will be loaded into the JVM, you can get to them through reflection program is running.

Here is an example of a custom annotations @Retention definitions:

@Retention(RetentionPolicy.RUNTIME)
@interface Test_Retention{
    
}

@Test_Retention
class MyAnnotation {
    public void getInfo(){
        
    }
}

The above code creates a Test_Retention annotation, and the annotation can be used to retain @Retention to specify Test_Retention program runs (RetentionPolicy.RUNTIME), MyAnnotation use @Test_Retention modified so that at runtime annotation information can be acquired by reflecting MyAnnotation.

@Documented If the class A notes annotation using @Documented yuan notes, then use javadoc generated classes A document will contain a corresponding annotation information.
    Example of use:

@Documented
@interface TestDocument{
    String doTestDocument();
}

@TestDocument (doTestDocument="保留注解信息测试")
class MyAnnotation {
    
    public void getInfo(){
        
    }
}

@Target the modified annotation specifies the range of the object, it can be used for arguments, parameters, methods, and other package information.
    @Target meta-annotation provides the following eight values:

    It is used to describe the type of annotation ElementType.ANNOTATION_TYPE

    The method of construction for the annotation ElementType.CONSTRUCTOR

    ElementType.FIELD for variable comment

    ElementType.LOCAL_VARIABLE for local variables notes

    ElementType.METHOD method for annotation

    ElementType.PACKAGE package for comment

    ElementType.PARAMETER process parameters for the annotation

    ElementType.TYPE for classes, interfaces, enumerations comment

Code Example:

@Target(ElementType.METHOD)
@interface TestMethodTarget{
    
}

@Target(ElementType.FIELD)
@interface TestFieldTarget{
    
}

@Target(ElementType.TYPE)
@interface TestTypeTarget{
    
}

TestMethodTarget only annotation method for annotation class, TestFieldTarget only for annotation class member variables, TestTypeTarget can be used for annotation class, interface (including type of annotation), or an enum declaration

@Inherited specify annotations can be inherited. @Inherited a class using the modified notes, then the notes will be used subclass of the class.
    Code Example:

@Inherited
@interface TestInherited{
    
}

@Repeatable same annotation can be used multiple times. For example, a person has a variety of hobbies, running, painting, watching movies and so on.
    Sample code:

@interface Persons {
    Person[]  value();
}


@Repeatable(Persons.class)
@interface Person{
    String hobby default "";
}


@Person(hobby="runing")
@Person(hobby="drawing")
@Person(hobby="watching movies")
public class Tom{

}

The above code, @ Repeatable annotated Person. @Repeatable brackets behind the class corresponding to one container annotation.
    What is the container notes it? The place is used to store other annotations. It is itself a comment.

Details of the above knowledge, and custom annotation syntax annotations. Now we look at how to use annotations for unit testing.

Use these notes to be reflected knowledge, knowledge of another article on reflection I look at “Java reflection using the summary.” After getting reflected by the object, the object method to invoke isAnnotationPresent contains the specified types of notes. Annotation

Sample code:

public class Marathonrunner {
    @RuningTest
    public void test5km(){
        System.out.println("进行5公里跑步测试");
    }

    public void test10km(){
        System.out.println("进行10公里跑步测试");
    }

    @RuningTest
    public void test21km(){
        System.out.println("进行21公里跑步测试");
    }

    public void test42km(){
        System.out.println("进行42公里跑步测试");
    }

}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface  RuningTest{

}


public class RuntestTool {
    public static void main(String args[]){
        Marathonrunner xiaoming = new Marathonrunner();

        Class clazz = xiaoming.getClass();

        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if(method.isAnnotationPresent(RuningTest.class)){
                try {
                    method.setAccessible(true);
                    method.invoke(xiaoming, null);

                } catch (Exception e) {

                }
            }
        }
    }
}

operation result:

进行21公里跑步测试
进行5公里跑步测试

The above code, we define a RuningTest notes, which do not have any variable. This annotation using @Retention and @Target meta-annotation modification, where the value of @Target meta-annotation of the provisions of this RuningTest comment only on the method, and @Retention meta-annotation value specifies the information at run time can get to annotations.

Defines a class mobilization Marathonrunner marathon far, there are four methods.

It defines a class designed for testing Marathonrunner athletes approach. If we want to test a class, simply add @RuningTest comment on that class, without @RuningTest annotated method will not be tested. test5km () and test21km () methods are added @RuningTest notes, they were tested.

Notes in spring, mybatis annotation GF application. Next spring application specifically written articles in speaking notes under.

to sum up:
    This article explains the concept notes, the concept of yuan notes, and how to customize annotations, notes and how to use their own definition of unit testing.

Leave a Reply