Annotations are not the program itself. They can be read during program compilation, class loading and runtime, and execute the corresponding processing. The format of the annotation is "@annotation name (parameter value)", which can be attached to packages, classes, methods and fields, and the annotation is accessed through the reflection mechanism.
@Override: Restrict subclasses to override methods
This annotation indicates that the method of the parent class is overridden. When a class overrides a parent class method, ensure that the subclass actually overrides the parent class method to avoid low-level errors
/** * 该注解标识覆盖的是其父类的方法,当子类重写父类方法时,确保子类确实重写了父类的方法,避免出现低级错误 * @return */ @Override public String toString() { return super.toString(); }
@Deprecated: The mark is obsolete
This An annotation indicates that a property, method, or class is obsolete (a program element that programmers are discouraged from using, usually because it is dangerous or because a better alternative exists). When other programs use the obsolete property, method or class, the compiler will give a warning (strikethrough).
/** * 该注解表示此方法已过时,存在危险,不推荐使用,其有代替方法,如果继续使用会通过删除线进行标识 */ @Deprecated public static void test() { System.out.println("标记已过时"); }
@SuppressWarnings (parameter): Suppress compiler warnings
The classes, methods and properties affected by this annotation will suppress the display of compiler warnings, and its parameters are mainly for Warning instructions and cancellation (unchecked), etc.
@SuppressWarnings("取消此类的所有警告") public class BuiltAnnotation { @SuppressWarnings("取消此属性的警告") private String username; @SuppressWarnings("取消此方法的警告") public static void main(String[] args) { // ... } }
The role of meta-annotation is to annotate other annotations. Java defines 4 standard meta-annotation types, which are used to provide support for other annotations. The scope and type are described, and other annotations can be customized through meta-annotations.
@Target: Describe the scope of use of annotations
For example, @Target(ElementType.METHOD) indicates that it acts on a method, @Target(ElementType.TYPE) indicates that it acts on Class or interface etc.
/** * @Target注解:描述注解的使用范围 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target { /** * 类或接口:ElementType.TYPE; * 字段:ElementType.FIELD; * 方法:ElementType.METHOD; * 构造方法:ElementType.CONSTRUCTOR; * 方法参数:ElementType.PARAMETER; * ... */ ElementType[] value(); }
@Retention: Indicates at what level the annotation information needs to be saved, used to describe the life cycle of the annotation
Usually customized annotations are Use @Retention(RetentionPolicy.RUNTIME), which is a runtime effect.
/** * @Retention:表示需要在什么级别保存该注解信息,用于描述注解的生命周期 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Retention { /** * RetentionPolicy.SOURCE:仅编译期,注解将被编译器丢弃。 * RetentionPolicy.CLASS:仅class文件,注释将由编译器记录在类文件中,但VM不需要在运行时保留,如果不指定则默认为class。 * RetentionPolicy.RUNTIME:运行期,注释将由编译器记录在类文件中,并由VM在运行时保留,因此可以反射读取。通常自定义的注解都是RUNTIME。 * 范围:RUNTIME>CLASS>SOURCE */ RetentionPolicy value(); }
@Document: Indicates that this annotation will be included in javadoc
##@Iherited: An annotation that defines whether a subclass can inherit the parent class definition.
@Inherited is only useful for annotations of the @Target(ElementType.TYPE) type, and can only be inheritance of class, and is invalid for inheritance of interface: 1.4 Custom annotationsDefine annotations
/** * 1. 使用@interface定义注解; * 3. 通过元注解配置该注解,配置注解的使用范围和生命周期等 * @author Loner */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Report{ /** * 2. 添加参数、默认值,如果没有默认值,就必须给参数赋值,一般把最常用的参数定义为value(),推荐所有参数都尽量设置默认值 * 形式为:参数类型 参数名(); */ int type() default 0; String value() default "LonerMJ"; }
Use annotations
@Report(type = 1, value = "test") public class CustomerAnnotation { @Report(type = 1, value = "test") public void testCustomerAnnotation() { System.out.println("测试自定义注解"); } }2. Reflection2.1 Reflection and Reflection mechanism
Reflection
Reflection (reflection) means that the program can get all the information of an object during runtime.Reflection mechanism
The reflection mechanism means that when the program is running, it obtains the content information of any class through the Reflection API, and can directly operate the internal properties and methods of any object. . 2.2 How to obtain the Class class and common methodsThe java.lang.Class class is the core class that implements reflection. After the class is loaded, a class will be generated in the method area of the heap memory. Class object (a class has only one Class object), this object contains the complete structural information of the class, and the structure of the class can be seen through this object.How to obtain the Class class
public class InstantiationClass { public static void main(String[] args) throws ClassNotFoundException { Teacher teacher = new Teacher("张三", "123456"); // 方式一:调用Class类的静态方法forName(String className) Class<?> c1 = Class.forName("com.loner.mj.reflection.Teacher"); // 方式二:已知某个类的实例,调用该实例的getClass()方法,getClass是Object类中的方法。 Class<? extends Teacher> c2 = teacher.getClass(); // 方式三:已知具体类,通过类的class属性获取,该方法最安全可靠,程序性能最高 Class<Teacher> c3 = Teacher.class; // 方式四:通过基本内置类型的包装类的TYPE属性获得CLass实例 Class<Integer> c4 = Integer.TYPE; // 方式五:通过当前子类的Class对象获得父类的Class对象 Class<?> c5 = c1.getSuperclass(); } }
Common methods of the Class class
Method function | |
---|---|
Returns the Class object of the specified class name | |
Call the parameterless constructor and return an instance of the Class object | |
Return this The name of the entity (class, interface, array class or void) represented by the Class object | |
Returns the Class object of the parent class of the current Class object | |
Returns the interface of the current Class object | |
Return the class loader of this class | |
Get the method name that matches the parameter list Method | |
Get all non-inherited methods | |
Get all non-private methods | |
Get the specified attribute | |
Get all properties | |
Get all non-private properties | |
Get the constructor method matching the parameter list | |
Get all constructors of the class | |
Return the specified annotation | |
Return all annotations |
The above is the detailed content of How to use annotations and reflection in Java. For more information, please follow other related articles on the PHP Chinese website!