Java进阶(1)——JVM的内存分配 & 反射Class类的类对象 & 创建对象的几种方式 & 类加载(何时进入内存JVM)& 注解 & 反射

Class —-用来表示Hello这个类

获取Class对象的几种方式
  • 类.class
  • Class.forName(“包名.类名”)
  • 对象.getClass()

在这里插入图片描述

class com.tianju.auth.reflect.Hello

package com.tianju.auth.reflect;

public class Hello {
    public Integer count(Integer a,Integer b){
        return a+b;
    }
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        int a = 3;
        Class<?> aClass = Hello.class; // ?泛型的写法,?未知类型
        Class<?> aClass1 = Class.forName("com.tianju.auth.reflect.Hello");
        Class<? extends Hello> aClass2 = new Hello().getClass(); // extends Hello 代表的hello的子集
        System.out.println(aClass);
        System.out.println(aClass1);
        System.out.println(aClass2);

        Hello o = (Hello) aClass.newInstance(); // 创建对象
        int count = o.count(1, 2);
        System.out.println(count);
    }
}

在这里插入图片描述

创建对象几种方式

new 看到new : new Book()

反射 Class.forName(“包名.类名”)

克隆(拷贝)

  • 继承的时候,可以将子类的访问控制符扩大,但不能缩小;子类不得比父类抛出更多,更大的异常。
  • 浅拷贝、深拷贝问题:

在这里插入图片描述

浅拷贝

在这里插入图片描述

    // protected:代表本包或者继承
    // 继承的时候,可以将子类的访问控制符扩大,但不能缩小;
    // 子类不能比父类抛出更多的异常
    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

深拷贝

在这里插入图片描述

    public Book deepClone(){
        Book book = new Book();
        Author au = new Author();
        au.setName(author.getName());
        book.setAuthor(au);
        book.setTitle(this.title);
        book.setPrice(this.price);
        return book;
    }

案例

Author.java实体类

package com.tianju.auth.reflect;

import lombok.Data;

@Data
public class Author {
    private String name;
}

Book.java实体类

implements Cloneable{ // 可以克隆的

package com.tianju.auth.reflect;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book implements Cloneable{ // 可以克隆的
    private String title;
    private Author author;
    public double price;

    static {
        System.out.println("book的静态代码块");
    }

    // protected:代表本包或者继承
    // 继承的时候,可以将子类的访问控制符扩大,但不能缩小;
    // 子类不能比父类抛出更多的异常
    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public Book deepClone(){
        Book book = new Book();
        Author au = new Author();
        au.setName(author.getName());
        book.setAuthor(au);
        book.setTitle(this.title);
        book.setPrice(this.price);
        return book;
    }
}


进行测试

在这里插入图片描述

package com.tianju.auth.reflect;

public class TestDemo{
    public static void main(String[] args) throws CloneNotSupportedException {
        Author author = new Author();
        author.setName("吴承恩");
        Book book = new Book("三国演义", author,12.56);
        Book book1 = book;

        System.out.println(book1==book);// == 两个引用是否指向同一个对象

        // clone创建了一个新的对象,只是值一样
        Book bookClone = (Book) book.clone();
        // 深拷贝,创建了新的对象,上面的浅拷贝,只是拷贝了引用
        Book deepClone = book.deepClone();

        System.out.println(bookClone==book);
        System.out.println("克隆前:"+book);
        System.out.println("克隆后:"+bookClone);

        author.setName("小柯基");
        System.out.println("修改后的原对象:"+book);
        System.out.println("修改后的clone对象:"+bookClone);

        // 深拷贝
        System.out.println("\*\*\*\*\*\*\*\*\*\*\*");
        System.out.println("深拷贝的方法:"+deepClone);
    }
}


序列化和反序列化

什么时候加载.class文件进入内存(JVM)

在这里插入图片描述

类的加载过程

在这里插入图片描述

连接:
  • 验证:格式检查->语义检查->字节码验证->符号引用验证
  • 准备:为静态变量分配内存并设置默认的初始值
  • 解析:符号引用替换为直接引用

cafe babe 魔术头

在这里插入图片描述

初始化:JVM对类进行初始化
  • 则是为标记为常量值的字段赋值的过程。换句话说,只对static修饰的变量或语句块进行初始化。
  • 如果类存在直接的父类并且这个类还没有被初始化,那么就先初始化父类。
  • 如果类中存在初始化语句,就依次执行这些初始化语句。

每一个类产生了一个唯一的对象Class, Class对象记录了类的基本信息。

如何获取Class对象【反射的基础】
  1. 对象.getClass()
  2. 类.class
  3. Class.forName(“包名.类名”)

在这里插入图片描述

类什么时候被加载

Hello h; // 此时没有用Hello,jvm并没有进行类加载

  • 看到new : new Book()
  • Class.forName: Class.forName(“包名.类名”)
  • 类加载器
package com.tianju.auth.reflect;

public class HelloTest1 {
    public static void main(String[] args) throws ClassNotFoundException {
        Hello h; // 此时没有用Hello,jvm并没有进行类加载
        System.out.println("\*\*\*\*\*\*\*\*\*\*");
        new Hello(); // new 的时候会加载到内存中
        System.out.println("\*\*\*\*\*\*\*\*\*\*");
        Class.forName("com.tianju.auth.reflect.Hello");

    }
}

package com.tianju.auth.reflect;

public class Hello {
    static {
        System.out.println("hello");
    }
    public Integer count(Integer a,Integer b){
        return a+b;
    }
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        int a = 3;
        Class<?> aClass = Hello.class; // ?泛型的写法
        Class<?> aClass1 = Class.forName("com.tianju.auth.reflect.Hello");
        Class<? extends Hello> aClass2 = new Hello().getClass();
        System.out.println(aClass);
        System.out.println(aClass1);
        System.out.println(aClass2);

        Hello o = (Hello) aClass.newInstance();
        int count = o.count(1, 2);
        System.out.println(count);

    }
}

怎么被加载?

双亲委托(派)机制

  • AppClassLoader (自定义的类)
  • ExtClassLoader
  • BootstrapClassLoader

A$B: B是A的内部类

在这里插入图片描述

A$B: B是A的内部类

在这里插入图片描述

另一种情况

在这里插入图片描述

在这里插入图片描述

双亲委托(委派)机制

好处:安全

在这里插入图片描述

在这里插入图片描述

例子:创建了java.lang.String报错

实际是加载的时候BootstrapClassLoader拒接加载

能编译,不能运行

在这里插入图片描述

配置这个是因为类加载,lib表示下面包都可以加载;或者配置指向rt里面,常用的string能在里面

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

反射

Class对象

Filed: 属性对象

Method: 方法对象

在这里插入图片描述

Car.java实体类

package com.tianju.auth.reflect;

public class Car {
    private String brand;
    private String color;
    private double price;

    public void run(String carName){
        System.out.println(carName+":I'm going to run");
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", color='" + color + '\'' +
                ", price=" + price +
                '}';
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

Method: 方法对象;

Filed: 属性对象

package com.tianju.auth.reflect;

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

public class TestReflect {
    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException {
        Car c = new Car();
        c.setBrand("BMW");
        c.setColor("red");
        c.setPrice(123456.78);

        /\*\*
 \* 属性
 \*/
        Class<Car> carClass = Car.class;
        Field[] declaredFields = carClass.getDeclaredFields(); // 获得所有的属性

        for(Field field:declaredFields){
            System.out.println(field.getName() + ": "+field);
            // Class com.tianju.auth.reflect.TestReflect can not access a member of
            // class com.tianju.auth.reflect.Car with modifiers "private"
            field.setAccessible(true);
            System.out.println(field.get(c));
        }

        /\*\*
 \* 方法
 \*/
        Method[] declaredMethods = carClass.getDeclaredMethods();
        for(Method method:declaredMethods){
            String methodName = method.getName();
            if (methodName.startsWith("get")){
                // method.invoke(c) 表示 Car c 调用这个方法
                System.out.println(methodName+": "+method.invoke(c));
            }

            if (methodName.equals("run")){
                method.invoke(c,"BMW");
            }
        }

    }
}


注解

注解的本质

本质就是标记一下

@Target({ElementType.TYPE}) // 作用在类上
@Target({ElementType.FIELD}) // 作用在属性上
@Target({ElementType.METHOD}) // 这个注解作用在方法上

package com.tianju.auth.reflect;

import java.lang.annotation.\*;

/\*\*
 \* 自定义注解:能找到指定的方法,进行指定的操作
 \*/
//@Target({ElementType.TYPE}) // 作用在类上
//@Target({ElementType.FIELD}) // 作用在属性上
@Target({ElementType.METHOD}) // 这个注解作用在方法上
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CarAnnotation {
    String name() default "";
}

反射+自定义注解案例

1.执行某些方法,不执行某些方法

在这里插入图片描述

CarAnnotation.java注解文件

package com.tianju.auth.reflect;

import java.lang.annotation.\*;

/\*\*
 \* 自定义注解:能找到指定的方法,进行指定的操作
 \*/
//@Target({ElementType.TYPE}) // 作用在类上
//@Target({ElementType.FIELD}) // 作用在属性上
@Target({ElementType.METHOD}) // 这个注解作用在方法上
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CarAnnotation {
    String name() default "";
}


Car.java文件

package com.tianju.auth.reflect;

public class Car {
    private String brand;
    private String color;
    private double price;

    @CarAnnotation(name = "myCar")
    public void run(String carName){
        System.out.println(carName+":I'm going to run");
    }

    @CarAnnotation(name = "yourCar")
    public void speedUp(){
        System.out.println("加速开。。。");
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", color='" + color + '\'' +
                ", price=" + price +
                '}';
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

执行注解的name是myCar的方法

CarAnnotation annotation = method.getDeclaredAnnotation(CarAnnotation.class);

“myCar”.equals(annotation.name())

在这里插入图片描述

package com.tianju.auth.reflect;

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

public class TestReflect {
    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException {
        Car c = new Car();
        c.setBrand("BMW");
        c.setColor("red");
        c.setPrice(123456.78);

        /\*\*
 \* 属性
 \*/
        Class<Car> carClass = Car.class;
        Field[] declaredFields = carClass.getDeclaredFields(); // 获得所有的属性

        for(Field field:declaredFields){
            System.out.println(field.getName() + ": "+field);
            // Class com.tianju.auth.reflect.TestReflect can not access a member of
            // class com.tianju.auth.reflect.Car with modifiers "private"
            field.setAccessible(true);
            System.out.println(field.get(c));
        }

        /\*\*
 \* 方法
 \*/
        Method[] declaredMethods = carClass.getDeclaredMethods();
        for(Method method:declaredMethods){
            String methodName = method.getName();
            if (methodName.startsWith("get")){
                // method.invoke(c) 表示 Car c 调用这个方法
                System.out.println(methodName+": "+method.invoke(c));
            }

            if (methodName.equals("run")){
                method.invoke(c,"BMW");
            }
        }

        /\*\*
 \* 注解:
 \*/
        for(Method method:declaredMethods){
            CarAnnotation annotation = method.getDeclaredAnnotation(CarAnnotation.class);
            if (annotation!=null){
                String name = annotation.name();
                System.out.println("注解值:"+name);
                if ("myCar".equals(annotation.name())){
                    method.invoke(c,"bmw");
                }
            }
        }

    }
}


2.模拟springBoot的自动注入@Autowired

在这里插入图片描述

Autowired.java注解实体类

package com.tianju.auth.reflect;

import java.lang.annotation.\*;

@Target({ElementType.FIELD}) // 作用在属性上
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
}


person.java实体类

field.set(person,o); // 给person 注入了 car 对象

package com.tianju.auth.reflect;

import java.lang.reflect.Field;
import java.util.Objects;

public class Person {

    @Autowired
    private Car car;

    public Car getCar(){
        return this.car;
    }

    @Override
    public String toString() {
        return "Person{" +
                "car=" + car +
                '}';
    }

    /\*\*
 \* 模拟 spring的实现过程
 \*/
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Class<Person> personClass = Person.class;
        Field[] declaredFields = personClass.getDeclaredFields();
        Person person = new Person();

        for(Field field:declaredFields){
            field.setAccessible(true);
            Autowired annotation = field.getDeclaredAnnotation(Autowired.class);


![img](https://img-blog.csdnimg.cn/img_convert/8ec6fb5d1b24b27d6755eda1bf7bb0c6.png)
![img](https://img-blog.csdnimg.cn/img_convert/8df92d51561c5f1af0eb353ae093eaf7.png)
![img](https://img-blog.csdnimg.cn/img_convert/46dd33b3c11a79f4eeca065aca5ffdac.png)

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上软件测试知识点,真正体系化!**

e Car car;

    public Car getCar(){
        return this.car;
    }

    @Override
    public String toString() {
        return "Person{" +
                "car=" + car +
                '}';
    }

    /\*\*
 \* 模拟 spring的实现过程
 \*/
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Class<Person> personClass = Person.class;
        Field[] declaredFields = personClass.getDeclaredFields();
        Person person = new Person();

        for(Field field:declaredFields){
            field.setAccessible(true);
            Autowired annotation = field.getDeclaredAnnotation(Autowired.class);


[外链图片转存中...(img-HO9q8IGX-1719227079173)]
[外链图片转存中...(img-HONLwJHa-1719227079174)]
[外链图片转存中...(img-tCmwNKPh-1719227079174)]

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上软件测试知识点,真正体系化!**

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值