Java 注解

栏目: Java · 发布时间: 6年前

内容简介:Java 注解学习笔记,原文:元注解即用来描述注解的注解。按 OO 的思想,假设注解是一个对象,那么谁来定义注解呢,那就是元注解。一表胜千言

Java 注解

Java 注解学习笔记,原文: Java中的注解原来是这样回事的

内置注解

  • @Override
  • @Deprecated
  • @SupperessWarnings

元注解

元注解即用来描述注解的注解。按 OO 的思想,假设注解是一个对象,那么谁来定义注解呢,那就是元注解。

@Target

一表胜千言

参数 说明
CONSTRUCTOR 构造器的声明
FIELD 域声明(包括enum实例)
LOCAL_VARIABLE 局部变量声明
METHOD 方法声明
PACKAGE 包声明
PARAMETER 参数声明
TYPE 类、接口(包括注解类型)或enum声明

@Retention

参数 说明
SOURCE 注解将被编译器丢弃
CLASS 注解在class文件中可用,但会被JVM丢弃
RUNTIME JVM将在运行期也保留注解,因此可以通过反射机制读取注解的信息

@Documented

@Inherited

如何定义注解

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

}

在后续的使用中直接 @Test 就可以使用我们自己定义的注解了。但是因为这个注解没有实现任何功能,所它什么也不会做。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    String name() default "";

    String catalog() default "";

    String schema() default "";

    UniqueConstraint[] uniqueConstraints() default {};

    Index[] indexes() default {};
}

注解处理器

定义一个简单的注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Person{
    String name() default "I don't have name";
	int age() default 21;
}

应用到实体类中:

public class MyLove {

    @Person(name = "My name is zhy")
    public String zhy(){
        return "zhy";
    }

    @Person(name = "My name is xyx", age = 19)
    public String xyx(){
        return "xyx";
    }

}

相应的注解处理器:

import java.lang.reflect.Method;
import java.util.List;

public class MyLoveTest {

	public static void myLoveTest(List<Integer> ages, Class<?> cl) {
		Method[] methods = cl.getDeclaredMethods();
		for (Method method :
				methods) {
			Person person = method.getAnnotation(Person.class);
			if (person != null) {
				System.out.println("My name is " + person.name() + "and I'm " + person.age());
				ages.remove(person.age());
			}
		}

		for (int i :
				ages) {
			System.out.print("Missing age is " + i);
		}
	}
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Mastering Regular Expressions, Second Edition

Mastering Regular Expressions, Second Edition

Jeffrey E F Friedl / O'Reilly Media / 2002-07-15 / USD 39.95

Regular expressions are an extremely powerful tool for manipulating text and data. They have spread like wildfire in recent years, now offered as standard features in Perl, Java, VB.NET and C# (and an......一起来看看 《Mastering Regular Expressions, Second Edition》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具