**Java注解:**又称JAVA标注,是JDK 5.0引入的一种注释机制。不是程序本身,可以对程序做出揭示,可以被其他程序读取。
格式:@+注释名(有些还可以添加参数)
**@Override *重写。如果发现其父类,或者是引用的接口中并没有该方法时,会报编译错误。
// @Override 重写注解
@Override
public String toString() {
return super.toString();
}
**@Deprecated:**标记过时方法。如果使用该方法,会报编译警告。
// @Deprecated 不推荐程序员使用,但是可以使用,或者存在更好的方式
@Deprecated
public static void test(){
System.out.println("Deprecated");
}
@SuppressWarnings: 指示编译器去忽略注释中声明的警告,需要参数。
// @SuppressWarnings 镇压警告
@SuppressWarnings("all")
public void test02(){
List list = new ArrayList<>();
}
元注解:负责注解其他注解
@Target: 描述注解的使用范围
**@Retention:**描述注解的生命周期
**@Documented:**该注解将被包含在javadoc中
**@Inherited:**子类可以继承父类中的该注解
import java.lang.annotation.*;
// 测试元注解
public class test02 {
@MyAnnotation
public void test(){
}
}
// 定义一个注解
// @Target 表示我们的注解可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})
// Retention 表示我们的注解在什么地方还有效
// 如果没有,就默认是.class
// runtime > class > sources
@Retention(value = RetentionPolicy.RUNTIME)
// Documented 表示是否将我们的注解生成在javadoc中
@Documented
// Inherited 子类可以继承父类的注解
@Inherited
// 定义注解是,@interface 是必须的
@interface MyAnnotation{
}
使用@interface自定义注解是,自动继承了java.lang.annotation.Annotation接口
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 自定义注解
public class Test03 {
// 注解可以显示赋值,如果没有默认值,就必须给注解赋值,没有顺序
@MyAnnotation2(name = "aa",sc)
public void test(){}
@MyAnnotation3("")
public void test2(){
}
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
// 注解的参数:参数类型 + 参数名();
String name();
// String name() default ""; 加默认值,可以不加参数
int age() default 0;
int id() default -1; // 如果默认值为-1,代表不存在
String[] schools() default {"aa","bb"};
}
@interface MyAnnotation3{
String value();
// 如果只有一个值,默认使用value,可以不用赋值
}
java Annotation 的组成中,有3个非常重要的主干类。分别是:
Annotation.java
package java.lang.annotation;
public interface Annotation {
boolean equals(Object obj);
int hashCode();
String toString();
Class<? extends Annotation> annotationType();
}
ElementType.java
package java.lang.annotation;
public enum ElementType {
TYPE, /* 类、接口(包括注释类型)或枚举声明 */
FIELD, /* 字段声明(包括枚举常量) */
METHOD, /* 方法声明 */
PARAMETER, /* 参数声明 */
CONSTRUCTOR, /* 构造方法声明 */
LOCAL_VARIABLE, /* 局部变量声明 */
ANNOTATION_TYPE, /* 注释类型声明 */
PACKAGE /* 包声明 */
}
RetentionPolicy.java
package java.lang.annotation;
public enum RetentionPolicy {
SOURCE, /* Annotation信息仅存在于编译器处理期间,编译器处理完之后就没有该Annotation信息了 */
CLASS, /* 编译器将Annotation存储于类对应的.class文件中。默认行为 */
RUNTIME /* 编译器将Annotation存储于class文件中,并且可由JVM读入 */
}
注解更详细描述:https://www.runoob.com/w3cnote/java-annotation.html
**反射:**加载类,获得类的各个组成部分
Class类:
// 通过反射获取类的class对象
Class c1 = Class.forName("User");
System.out.println(c1);
Class c2 = Class.forName("User");
Class c3 = Class.forName("User");
// 一个类在内存中只有一个class对象
// 一个类被加载后,类的整个构造都会被封装在class对象中
System.out.println(c2.hashCode());
System.out.println(c3.hashCode());
获得class类型实例:
// 方式一: 通过对象获得
Class c1 = person.getClass();
System.out.println(c1.hashCode());
// 方式二:forname获得
Class c2 = Class.forName("Student");
System.out.println(c2.hashCode());
// 方式三:通过类名.class获得
Class c3 = Student.class;
System.out.println(c3.hashCode());
// 方式四:基本内置类型的包装类都有一个Type属性
Class c4 = Integer.TYPE;
System.out.println(c4);
// 获得父类类型
Class c5 = c1.getSuperclass();
Syste.out.println(c5);
加载: 将class文件字节码呢容加载到内存中,并将这些静态数据转换成方法去的运行时数据结构,然后生成一个代表这个类的java.lang.Class对象
链接: 将java类的二进制代码合并到JVM的运行状态之中的过程。
验证:确保加载的类信息符合JVM规范,没有安全方面的问题
准备:正式为类变量分配内存并设置类变量默认初始值的阶段,这些内存都将在方法区中进行分配
解析:虚拟机常量池的符号引用(常量名)替换为直接引用(地址)的过程
初始化:
// 测试类什么时候初始化
public class Test06 {
static {
System.out.println("Main类被加载");
}
public static void main(String[] args) {
// 1.主动引用
// Son son = new Son();
// 反射也会产生主动引用
try {
Class.forName("Son");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Father{
static {
System.out.println("父类被加载");
}
}
class Son extends Father{
static {
System.out.println("子类被加载");
m = 300;
}
static int m = 100;
static final int M = 1;
}
什么时候会发生类初始化?
类的主动引用(一定会发生类的初始化)
类的被动引用(不会发生类的初始化)
**类加载器的作用:**把类装载进内存。有引导类加载器、扩展类加载器、系统类加载器。
public class Test07 {
public static void main(String[] args) throws ClassNotFoundException {
// 获取系统类的加载器
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);
// 获取系统类加载器的父类加载器 --> 扩展类加载器
ClassLoader parent = systemClassLoader.getParent();
System.out.println(parent);
// 获取扩展类加载器的父类加载器 --> 根加载器
ClassLoader parent1 = parent.getParent();
System.out.println(parent1);
// 测试当前类是哪个加载器加载的
ClassLoader classLoader = Class.forName("Test07").getClassLoader();
System.out.println(classLoader);
// 测试JDK内置的类是谁加载的
classLoader = Class.forName("java.lang.Object").getClassLoader();
System.out.println(classLoader);
// 如何获得系统加载器可以加载的路径
System.out.println(System.getProperty("java.class.path"));
// 双亲委派机制
// java.lang.String -->
}
}
获取运行时类的完整结构:
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test08 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("User");
// User user = new User();
// c1 = user.getClass();
// 获得类的名字
System.out.println(c1.getName()); // 获得包名 + 类名
System.out.println(c1.getSimpleName()); // 获得类名
// 获得类的属性
System.out.println("+++++++++++++++++++++++++++++++");
Field[] fields = c1.getFields(); // 只能找到public属性
fields = c1.getDeclaredFields(); // 找到全部的属性
for(Field field: fields){
System.out.println(field);
}
Field name = c1.getDeclaredField("name");
System.out.println(name);
// 获得类的方法
System.out.println("+++++++++++++++++++++++++++++++++");
Method[] methods = c1.getMethods(); // 获得本类及其父类的全部public方法
for(Method method: methods){
System.out.println("正常的:"+method);
}
methods = c1.getDeclaredMethods(); // 获得本类的所有方法
for(Method method : methods){
System.out.println("getDeclareMethods:"+method);
}
// 获得指定方法
Method getName = c1.getMethod("getName", null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
// 获得指定的构造器
System.out.println("+++++++++++++++++++++++++++");
Constructor[] constructors = c1.getConstructors();
for(Constructor constructor : constructors){
System.out.println("#"+constructor);
}
constructors = c1.getDeclaredConstructors();
for(Constructor constructor : constructors){
System.out.println("#" + constructor);
}
// 获得指定的构造器
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
System.out.println("指定:"+declaredConstructor);
}
}
性能对比:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
// 分析性能问题
public class Test10 {
// 普通方式调用
public static void test01(){
User user = new User();
long startTime = System.currentTimeMillis();
for(int i = 0; i < 1000000000;i++){
user.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方法执行10亿次:"+(endTime-startTime)+"ms");
}
// 反射方式调用
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
long startTime = System.currentTimeMillis();
for(int i = 0; i < 1000000000;i++){
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射方法执行10亿次:"+(endTime-startTime)+"ms");
}
// 反射方式调用 关闭检测
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
getName.setAccessible(true);
long startTime = System.currentTimeMillis();
for(int i = 0; i < 1000000000;i++){
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();
System.out.println("关闭检测执行10亿次:"+(endTime-startTime)+"ms");
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test01();
test02();
test03();
}
}
获取泛型:
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
// 通过反射获取泛型
public class Test11 {
public void test01(Map<String, User> map, List<User> list){
System.out.println("test01");
}
public Map<String, User> test02(){
System.out.println("test02");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method method = Test11.class.getMethod("test01", Map.class, List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType: genericParameterTypes){
System.out.println("#" + genericParameterType);
if(genericParameterType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for(Type actualTypeArgument : actualTypeArguments){
System.out.println(actualTypeArgument);
}
}
}
method = Test11.class.getMethod("test02", null);
Type genericReturnType = method.getGenericReturnType();
if(genericReturnType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for(Type actualTypeArgument : actualTypeArguments){
System.out.println(actualTypeArgument);
}
}
}
}
获取注解信息:
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Test12 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("Student2");
// 通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for(Annotation annotation : annotations){
System.out.println(annotation);
}
// 获得注解的value值
Tablekuang tablekuang = (Tablekuang)c1.getAnnotation(Tablekuang.class);
String value = tablekuang.value();
System.out.println(value);
// 获得类指定的注解
Field f = c1.getDeclaredField("name");
Filekuang annotation = f.getAnnotation(Filekuang.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
@Tablekuang("db_student")
class Student2{
@Filekuang(columnName = "db_id", type = "int", length = 10)
private int id;
@Filekuang(columnName = "db_age", type = "int", length = 10)
private int age;
@Filekuang(columnName = "db_name", type = "varchar", length = 3)
private String name;
public Student2(){
}
public Student2(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student2{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
// 类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Tablekuang{
String value();
}
// 属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Filekuang{
String columnName();
String type();
int length();
}
根据B站UP主狂神说Java的JAVA注解和反射所做笔记。视频地址