Java foundation - notes, reflection

First, annotation (Annotation)

1. What is a comment?

  JDK5 from the beginning, Java increased Annotation (annotation), Annotation is a special code tags that can be compiled, class loading, be read runtime and executes the corresponding processing.

2, Annotation and notes the difference between:

  (1) Annotation not the program itself, can be explained on the program, can be understood here as a comment. Annotation but may be other programs (such as compilers) is read and processed.
  (2) Notes and comments biggest difference is the presence of the annotation process to be handled, that is the annotation program it will be handled.

3, annotation format:

  (1) in the form of "Notes @ name" exists in the code.
  (2) can be attached on top of the annotation program elements (packages, classes, constructors, methods, member variables, parameters, local variables), for additional auxiliary information, data can be accessed via reflection.
  (3) Annotation not run, its only member variables, no way. Annotation is similar to the public, final status and other modifiers, part of program elements belong to, but not as a program element.

4, common notes:

  (1) @Override
    defined in java.lang.Override, the only method for modifying this annotation, which denotes rewriting method of a parent class.

【举例:】
 @Override
 public String toString() {
     return "Hello";
}

  (2)@Deprecated

    Java.land.Deprecated definition, then this annotation can be used to modify the methods, properties, classes, indicating that the method, class, attribute deprecated (abandoned). In the method, class, there will be a line through the attribute (the form toString () ).

【举例:】
@Deprecated
public String toString() {
    return "TimerTaskDemo []";
}

  (3) @SuppressWarnings
    defined java.lang.SuppressWarnings, a warning for preventing compile-time. You need to set the parameters of its use.

Parameters are:] 
deprecation, using outdated warning class or method. 
an unchecked, performed when an abnormality unchecked conversion, such as a set of generic unspecified. 
fallthrough, when penetration occurs in the case of the switch statement warning. 
path, when the class path, warning source file path does not exist. 
serial, serializable class warning lack serialVersionUID. 
finally , warning of any finally can not be completed. 
all, all of the above warning. 

[Format:] 
@SuppressWarnings ( "All" ) 
or 
@SuppressWarnings (value = { "Serial", "an unchecked"})

 

5 yuan notes:

  The role of (1) a meta-annotation is responsible for the annotation of other notes. Java5.0 standard defines four meta-annotation type, which are used to provide other types of annotation specified. Present in java.lang.annotation in.

  (2) meta-annotation Category:
    @Target
    @Retention
    @Documented
    @ Inherited

  (3) @Target membered Note:
    for describing the use of annotations. Annotation may be used for packages, types (classes, interfaces, enumerations, Annotation type), a member type (method, constructor, member variables enumerated value), method arguments and local variables (such as a loop variable, the catch parameter). Use a target in the Annotation type declaration can be more clear that it modifies the target.

[Format:]
 public @ interface the Target 
{ 
  the ElementType [] value (); 
} 

Parameters: the ElementType] 
CONSTRUCTOR: constructor is used to describe 
FIELD: Description member variables for 
LOCAL_VARIABLE: local variables used to describe 
the METHOD: The method for describing 
PACKAGE : used to describe the package 
pARAMETER: parameters for describing 
tYPE: class used to describe the interface (including type of annotation), or an enum declaration 

Examples:] 
@Target ({java.lang.annotation.ElementType.TYPE, java.lang.annotation .ElementType.FIELD, java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.PARAMETER, java.lang.annotation.ElementType.CONSTRUCTOR, java.lang.annotation.ElementType.LOCAL_VARIABLE})

  (4) @Retention membered Note:
    for describing an annotation lifecycle. Some Annotation appear only in the source code, the compiler is discarded; others was compiled class files; Annotation compiled class files in the virtual machine may be ignored, while others are in class when loaded It is read (note does not affect the implementation of the class, because of the use of the Annotation class and are separated). Using this meta-Annotation Annotation can limit the "life cycle."

[Format:]
 public @ interface Retention 
{ 
  RetentionPolicy value (); 
} 

Parameters: RetentionPoicy] 
the SOURCE: valid in the source file (i.e., the source file remains) 
the CLASS: valid class file (i.e., class reserved) 
RUNTIME: when run effective (i.e. reserved running, can be read by reflection) 

Examples:] 
@Retention (RetentionPolicy.SOURCE)

  (5) @Documented membered Note:
    a description of other types of annotation program should be as members of the public API is labeled, it can be, for example, such tools javadoc of documentation. Documented is a marker annotation, no members.

  (6) @Inherited yuan Notes:
    @ Inherited meta-annotation is a marker annotation, @ Inherited describes a certain type of indexed is inherited. If using a modified @Inherited annotation type is used for a class, then this annotation is used in a subclass of this class.
Note:
    @ Inherited Annotation type of class is annotated subclass inherits. Class does not inherit from annotation methods it from overloading it implements interface inheritance annotation, method.
    When @Inherited annotation type annotation of the annotation is Retention RetentionPolicy.RUNTIME, the reflected API enhances this inheritance. If we use java.lang.reflect to query a @Inherited annotation type of annotation, reflecting code checks will start work: check the class and its parent class, until you find designated annotation types are found, or to reach the top class inheritance structure.

 

6, custom annotation:

  (1) custom annotations need to use @interface used to declare a comment, it will automatically inherit java.lang.annotation.Annotation interface.

[Format:]
 public @ interface annotation definition body {name} 
[or:] 
public @ interface annotation {name 
  type value () default default value;    // this is a parameter, not an abstract method. 
} 

Wherein the definition body is declared a substantial configuration parameters (Note: Here, the method is not abstract). 
1 , the method name refers to the name of the parameter.
2, return type refers to the type of the parameter (only basic types, Class, String, enum , the Annotation type, and one or more arrays of all types).
3 , can declare the default value of the parameter by default.
4 , if only one parameter, then the parameter name (method name) generally value.
5, only public, default permissions to two modifiers.  

  (2) Method:

Or a method of determining whether a class annotated
     Boolean isAnnotationPresent (Class <? The extends the Annotation> annotationClass) 

obtain annotation object
     <A the extends Annotation> A getAnnotation (Class <A> annotationClass)   // Get the specified annotation 
    the Annotation [] getAnnotations ()   // get the current All annotations on the element
【举例:】
package com.test;

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table {
    String value();
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldDemo {
    String columnName() default "";

    String type() default "";

    int length() default 10;
}

@Table("student")
class Student {
    @FieldDemo(columnName = "id", length = 10, type = "int")
    private int id;

    @FieldDemo(columnName = "name", length = 20, type = "varchar")
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class AnnotationDemo {
    public static void main(String[] args) {
        try {
            // 获取Student类的信息
            Class classDemo = Class.forName("com.test.Student");
            // Class<Student> classDemo = (Class<Student>)Class.forName("com.test.Student");
            System.out.println (classDemo); // output com.test.Student class 

            // get all annotations on the current element, it is retrieving the @Table 
            the Annotation [] = Annotations classDemo.getAnnotations ();
             for (the Annotation Annotation : annotations) { 
                System.out.println (annotation); 
            } // output com.test.Table @ (value = Student) 

            // direct access to a specified annotation 
            the Table Table = (the Table) classDemo.getAnnotation (the Table. class ) ; 
            System.out.println (table.value ()); // output Student 

            // get property class annotation 
            Field field = classDemo.getDeclaredField ( "name");
            // 获取指定注解
            FieldDemo fieldDemo = field.getAnnotation(FieldDemo.class);
            // 输出name varchar 20
            System.out.println(fieldDemo.columnName() + " " + fieldDemo.type() + " " + fieldDemo.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

Second, reflection

1. What is a reflection?

  JAVA reflection means is in the operating state, for any class, are made known to all properties and methods of this class; for any object, are able to call any of its methods and properties; i.e. dynamically obtain such information and dynamic call the object methods feature called reflection java language.
  JAVA classes associated with reflection on java.lang.reflect package.

2, Class class

  Class object contains the complete information on the structure of a class. , Can be operated by a Class object class, that is reflected.
  (1) Rules:
    Class is defined as a class have generics.
    Instance of class Class represent classes and interfaces Java applications running in.
    No Class public class constructor.
    Class object when loading classes are Java Virtual Machine and the automatic construction method defineClass by calling the class loader.
    A class has only one Class object.

  (2) Examples of the built-in class (class object):

byte.classshort.classint.classlong.classchar.classfloat.classdouble.classboolean.classvoid.class.
注:
int.class != Integer.classint.class == Integer.Type  。

  (3) For the array type class instance:
    each array is mapped to a Class object belonging to a class, all array elements having the same type and dimension of the Class objects are shared.

int[] a = new int[100];
int[] b = new int[10];
long[] c = new long[10];
int[][] d = new int[10][2];
System.out.println(a.getClass());//输出class [I
System.out.println(b.getClass());//输出class [I
System.out.println(c.getClass());//输出class [J
System.out.println(d.getClass());//输出class [[I
System.out.println(a.getClass() == b.getClass());//输出true

  (4) Get Class example of a method:

[Method 1:] 
based on the passed parameter a dynamically loaded class, the class and do initialization. 
    The Class.forName () method 

[Method 2:] 
obtained referents true runtime object (polymorphic routine is returned class name of the subclass). 
    Class.getClass () method 

[Method 3:] 
JVM class loader using class A, class A will be loaded into memory (the proviso that: A class is loaded into memory yet), the initialization operation do not class A class returns. class a class of objects. 
    A.class property

  (5) to create objects by Class instance:

The Class.newInstance () method. Calling the default constructor, to obtain an instance 

Class.newInstance methods and new distinction 
newInstance: weak type. ineffective. Only call the constructor with no arguments. 
new new : strong typing. Relatively efficient. You can call any public structure.

  (6) commonly used methods:

[Obtaining constructor:] 
Constructor <T> getDeclaredConstructor (<?> Class ...) for the specified constructor 
Constructor <?> [] GetDeclaredConstructors () to get all constructors (declaration order) 
Constructor <T> getConstructor (Class <? > ...) to obtain permission for the specified public constructor 
constructor <>? [] getConstructors () to obtain permission for the public of all constructors 

[obtaining ordinary method (member method):] 
method [] getDeclaredMethods () to get the class All methods defined (does not include the parent class inheritance) 
method, getDeclaredMethod (String name, class <?> ... parameterTypes) according to a specified method defined in the class (does not include the parent class inheritance) 
method, [] getMethods () to get permission to All public methods (including the parent class inheritance) 
method, getMethod (String name, class <?> ... parameterTypes) to obtain permission for the public of the specified method (containing parent class inheritance)

[Obtaining properties (member variables):] 
Field [] getDeclaredFields () to get all the properties defined in the class (does not include inherited) 
Field, getDeclaredField (String name) for the specified property defined in the class (does not include inherited) 
Field, [] getFields () to get all the public property in the class (including inherited) 
Field, getField (String name) get the class specified public property (including inheritance) 

[obtaining inner class:] 
class <?> [] getDeclaredClasses () to get all internal class (does not include inherited) 
class <?> [] getClasses () to get all the permissions for the public within the class (including inherited) 

[other:] 
package getPackage () to obtain package Object 
String getName () to get the full name of the class, that package name + class name 
referred String getSimpleName () to get the class, namely the class name 
class <? Super T> getSuperclass () to get a class that inherits 
class <?> [] getInterfaces () to get the interface

  Operation (7) is configured to obtain, can be performed

  Operation (8) The method of obtaining a member, can be performed

  After the operation (9) to obtain the member variable, that can be made

package com.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

class Teacher {
    private String name;
    private int age;

    public Teacher() {
    }

    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class ReflectionDemo {
    public static void main(String[] args) {
        try {
            // 加载Teacher.class对象
            Class<Teacher> teacherClass = (Class<Teacher>) Class.forName("com.test.Teacher");

            // 获取无参构造器,若Teacher类没有无参构造方法,则会报错
            Teacher teacher = teacherClass.newInstance();
            System.out.println(teacher + ", " + teacher.getName() + ", " + teacher.getAge());

            // 获取有参构造器
            Constructor<Teacher> constructor = teacherClass.getDeclaredConstructor(String.class, int.class);
            Teacher teacher2 = constructor.newInstance("tom", 20);
            System.out.println(teacher2 + ", " + teacher2.getName() + ", " + teacher2.getAge());

            // 获取成员方法
            Teacher teacher3 = teacherClass.newInstance();
            Method method = teacherClass.getDeclaredMethod("setAge", int.class);
            method.invoke(teacher3, 30);
            System.out.println(teacher3.getAge());

            Method method2 = teacherClass.getDeclaredMethod("getAge");
            System.out.println(method2.invoke(teacher3));

            // 获取成员变量
            Teacher teacher4 = teacherClass.newInstance();
            Field field = teacherClass.getDeclaredField("age");
            field.setAccessible(true);// 忽略安全检查,可以获取private类型的数据,破坏封装性。
            System.out.println(field.get(teacher4));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

【结果:】
com.test.Teacher@2a139a55, null, 0
com.test.Teacher@15db9742, tom, 20
30
30
0

3、反射机制性能问题

  setAccessible,是启用和禁用安全检查的开关,其值为true时,表示禁用Java语言访问的安全性检查,为false时,表示启用安全性检查,将其值设为true,可以提高反射的效率。

 

未完待续。。。。

 

Guess you like

Origin www.cnblogs.com/l-y-h/p/11111539.html