JavaSE-注解与反射知识点笔记

1,注解

Java.Annotation

内置注解

元注解

package annotation;

import java.lang.annotation.*;

//测试元注解
@MyAnnotation
public class Test02 {
          
   

        public  void  test(){
          
   }
}

//定义一个注解
//Target表示我们的注解可以用在哪些地方
@Target(value = {
          
   ElementType.METHOD,ElementType.TYPE})

//Retention表示我们的注解在什么地方还有效
//runtime>class>sources
@Retention(value = RetentionPolicy.RUNTIME)

//Documented表示是否将我们的注解生成在JAVAdoc中
@Documented

//Inherited子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
          
   

}

自义定注解

package 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 = "cdd")
    public void test(){
          
   

    }

    @MyAnnotaion3("cdd" )
    public void test2(){
          
   

    }


}

@Target({
          
   ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
          
   
    //注解的参数:参数类型+参数名()
    String name() default "";
    int age() default 0;
    int id() default -1;//如果默认值为-1,代表不存在

    String[] schools() default {
          
   "人工智能学院","重庆文理学院"};
}
@Target({
          
   ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotaion3{
          
   
    String value();

}

2,反射

Java.Reflection

1,概述

2,Class

package reflection;
//测试class类的创建方式有哪些
public class Test02 {
          
   
    public static void main(String[] args) throws ClassNotFoundException {
          
   
        Person person = new Student();
        System.out.println("这个人是:"+person.name);

        //方式一:通过对象获得
        Class c1 = person.getClass();
        System.out.println(c1.hashCode());

        //方式二:通过forName获得
        Class c2 = Class.forName("reflection.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();
        System.out.println(c5);

    }

}

class Person{
          
   
    public String name;

    public Person() {
          
   
    }

    public Person(String name) {
          
   
        this.name = name;
    }

    @Override
    public String toString() {
          
   
        return "Person{" +
                "name=" + name +  +
                };
    }
}
class Student extends Person{
          
   
    public Student(){
          
   
        this.name="学生";
    }
}
class Teacher extends Person{
          
   
    public Teacher() {
          
   
        this.name="老师";
    }
}

3,内存分析

4,类的初始化

5,类加载器

注:本笔记于b站up主“遇见狂神说” https://www.bilibili.com/video/BV1p4411P7V3 处学习记录,仅供学习与参考

经验分享 程序员 微信小程序 职场和发展