JVM-字节码应用

news2024/11/17 11:44:54

一、字节码的应用远超你的想象

二、ASM介绍与读取字节码实战

用CoreAPI解析和TreeAPI都能做字节码解析,区别,TreeAPI必须读取完整字节码信息,才能做解析。

下面代码,使用CoreAPI做解析:

package asm;

public class MyMain {

    public int a = 10;
    public int b = 11;

    public void test1() {

    }

    public void test2() {

    }

    public static void main(String[] args) {

    }
}
package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {

    public static byte[] getContent(String filePath) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        fi.close();
        return buffer;
    }

    public static void writeByteArrayToFile(String filePath, byte[] byteArray) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
            fileOutputStream.write(byteArray);
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
package asm;



import jdk.internal.org.objectweb.asm.*;
import util.FileUtil;

import java.io.IOException;

import static jdk.internal.org.objectweb.asm.Opcodes.ASM5;

/**
 * case1 读取一个字节码里的方法等信息
 */
public class ASMReadClassTest {

    public static void getClassInfoByCoreAPI(byte[] bytes) {
        ClassReader classReader = new ClassReader(bytes);
        ClassWriter classWriter = new ClassWriter(0);
        ClassVisitor classVisitor = new ClassVisitor(ASM5, classWriter) {
            @Override
            public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
                super.visit(version, access, name, signature, superName, interfaces);
            }

            @Override
            public void visitSource(String source, String debug) {
                System.out.println("source in visitSource:" + source);
                super.visitSource(source, debug);
            }

            @Override
            public void visitOuterClass(String owner, String name, String desc) {
                super.visitOuterClass(owner, name, desc);
            }

            @Override
            public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                return super.visitAnnotation(desc, visible);
            }

            @Override
            public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
                return super.visitTypeAnnotation(typeRef, typePath, desc, visible);
            }

            @Override
            public void visitAttribute(Attribute attr) {
                System.out.println("visitAttribute attr: " + attr);
                super.visitAttribute(attr);
            }

            @Override
            public void visitInnerClass(String name, String outerName, String innerName, int access) {
                super.visitInnerClass(name, outerName, innerName, access);
            }

            @Override
            public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
                System.out.println("visitField filed: " + name);
                return super.visitField(access, name, desc, signature, value);
            }

            @Override
            public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
                System.out.println("visitMethod method: " + name);
                return super.visitMethod(access, name, desc, signature, exceptions);
            }

            @Override
            public void visitEnd() {
                System.out.println("visitEnd .... ");
                super.visitEnd();
            }
        };


        classReader.accept(classVisitor, ClassReader.SKIP_DEBUG);

    }
//
//
//    public static void getClassInfoByTreeAPI(byte[] bytes) {
//        ClassReader classReader = new ClassReader(bytes);
//        ClassNode classNode = new ClassNode();
//        classReader.accept(classNode, ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE);
//
//        List<FieldNode> fieldNodeList = classNode.fields;
//        for (FieldNode fieldNode : fieldNodeList) {
//            System.out.println("field node :" + fieldNode.name);
//        }
//
//        List<MethodNode> methodNodeList = classNode.methods;
//        for (MethodNode methodNode : methodNodeList) {
//            System.out.println("method :" + methodNode.name);
//        }
//
//    }

    public static void main(String[] args) throws IOException {
        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMain.class";
        byte[] bytes = FileUtil.getContent(filePath);
//        第一种方式,通过CoreAPI获得字节码信息
        getClassInfoByCoreAPI(bytes);
//        getClassInfoByTreeAPI(bytes);

    }
}

解释:

ASM5 - ASM的版本;

classWriter - 即上面的classWriter,处理完成后,将信息携带哪里去。

classReader.accept方法的第一个参数是classVisitor,即上面定义的classVisitor, 第二个ClassReader.SKIP_DEBUG,操作的时候,哪些信息不看,这里是跳过debug信息,一般来说设置忽略debug信息就可以了 。

对照MyMain.class

package asm;

public class MyMain {

    public int a = 10;
    public int b = 11;

    public void test1() {

    }

    public void test2() {

    }

    public static void main(String[] args) {

    }
}

输出内容跟实际Java类内容是一样的。

用TreeAPI做字节码信息解析:

package asm;



import jdk.internal.org.objectweb.asm.*;
import jdk.internal.org.objectweb.asm.tree.ClassNode;
import jdk.internal.org.objectweb.asm.tree.FieldNode;
import jdk.internal.org.objectweb.asm.tree.MethodNode;
import util.FileUtil;

import java.io.IOException;
import java.util.List;

import static jdk.internal.org.objectweb.asm.Opcodes.ASM5;

/**
 * case1 读取一个字节码里的方法等信息
 */
public class ASMReadClassTest {

//    public static void getClassInfoByCoreAPI(byte[] bytes) {
//        ClassReader classReader = new ClassReader(bytes);
//        ClassWriter classWriter = new ClassWriter(0);
//        ClassVisitor classVisitor = new ClassVisitor(ASM5, classWriter) {
//            @Override
//            public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
//                super.visit(version, access, name, signature, superName, interfaces);
//            }
//
//            @Override
//            public void visitSource(String source, String debug) {
//                System.out.println("source in visitSource:" + source);
//                super.visitSource(source, debug);
//            }
//
//            @Override
//            public void visitOuterClass(String owner, String name, String desc) {
//                super.visitOuterClass(owner, name, desc);
//            }
//
//            @Override
//            public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
//                return super.visitAnnotation(desc, visible);
//            }
//
//            @Override
//            public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
//                return super.visitTypeAnnotation(typeRef, typePath, desc, visible);
//            }
//
//            @Override
//            public void visitAttribute(Attribute attr) {
//                System.out.println("visitAttribute attr: " + attr);
//                super.visitAttribute(attr);
//            }
//
//            @Override
//            public void visitInnerClass(String name, String outerName, String innerName, int access) {
//                super.visitInnerClass(name, outerName, innerName, access);
//            }
//
//            @Override
//            public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
//                System.out.println("visitField filed: " + name);
//                return super.visitField(access, name, desc, signature, value);
//            }
//
//            @Override
//            public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
//                System.out.println("visitMethod method: " + name);
//                return super.visitMethod(access, name, desc, signature, exceptions);
//            }
//
//            @Override
//            public void visitEnd() {
//                System.out.println("visitEnd .... ");
//                super.visitEnd();
//            }
//        };
//
//
//        classReader.accept(classVisitor, ClassReader.SKIP_DEBUG);
//
//    }


    public static void getClassInfoByTreeAPI(byte[] bytes) {
        ClassReader classReader = new ClassReader(bytes);
        ClassNode classNode = new ClassNode();

        //如果需要忽略多个,写法如下
        classReader.accept(classNode, ClassReader.SKIP_DEBUG|ClassReader.SKIP_CODE);

        List<FieldNode> fieldNodeList = classNode.fields;
        for (FieldNode fieldNode: fieldNodeList) {
            System.out.println("field node :" + fieldNode.name);
        }

        List<MethodNode> methodNodeList = classNode.methods;
        for(MethodNode methodNode: methodNodeList){
            System.out.println("method node :" + methodNode.name);
        }

    }

    public static void main(String[] args) throws IOException {
        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMain.class";
        byte[] bytes = FileUtil.getContent(filePath);
//        第二种方式,通过TreeAPI获得字节码信息
        getClassInfoByTreeAPI(bytes);
//        getClassInfoByCoreAPI

    }
}
/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=56427:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/rt.jar:/Users/mac/IdeaProjects/OOM/JVMSample/target/classes:/Users/mac/repo/org/openjdk/jol/jol-core/0.9/jol-core-0.9.jar asm.ASMReadClassTest
field node :a
field node :b
method node :<init>
method node :test1
method node :test2
method node :main

Process finished with exit code 0

三、基于ASM增加属性实战

//通过CoreAPI增加属性

package asm;
import org.objectweb.asm.*;
import util.FileUtil;

import java.io.IOException;

import static org.objectweb.asm.Opcodes.*;

public class ASMAddFieldClassTest {

    /**
     * 方法1,通过core API 增加一个String类型的变量xyz
     *
     * @param bytes
     */
    public static void editClassInfoByCoreAPI(byte[] bytes) {

        ClassReader classReader = new ClassReader(bytes);
        ClassWriter classWriter = new ClassWriter(0);
        ClassVisitor classVisitor = new ClassVisitor(ASM5, classWriter) {

            @Override
            public void visitEnd() {
                //todo 我们的目标是增加一个属性,其他都不需要动,所以按照这个思路,其他方法都不需要改动,只要在这个结束方法增加一个属性即可
                super.visitEnd();
                FieldVisitor fieldVisitor = super.visitField(ACC_PUBLIC, "xyz", "Ljava/lang/String;", null, null);
                if(fieldVisitor != null){
                    fieldVisitor.visitEnd();
                }

            }
        };

        classReader.accept(classVisitor, ClassReader.SKIP_DEBUG);

        //拿到修改好的字节码,重新写到一个文件里去
        byte[] newBytes = classWriter.toByteArray();

        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMainNew.class";
        FileUtil.writeByteArrayToFile(filePath, newBytes);

    }

//    /**
//     * 第二种方式,听过TreeAPI来增加字段
//     *
//     * @param bytes
//     */
//    public static void editClassInfoByTreeAPI(byte[] bytes) {
//        ClassReader classReader = new ClassReader(bytes);
//        ClassNode classNode = new ClassNode();
//        classReader.accept(classNode, ClassReader.SKIP_DEBUG);
//        FieldNode fieldNode = new FieldNode(ACC_PUBLIC|ACC_STATIC|ACC_FINAL, "xyz", "Ljava/lang/String;", null, null);
//        classNode.fields.add(fieldNode);
//
//        ClassWriter classWriter=new ClassWriter(0);
//        classNode.accept(classWriter);
//        byte[] newBytes=classWriter.toByteArray();
//
//        String filePath = "/Users/liuqingchao/Desktop/my_code/jvm_imooc/out/production/jvm_imooc/main/java/ch14_bytecode_application/asm/MyMainTree.class";
//        FileUtil.writeByteArrayToFile(filePath, newBytes);
//
//    }


    public static void main(String[] args) throws IOException {
        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm//MyMain.class";
        byte[] bytes = FileUtil.getContent(filePath);
        editClassInfoByCoreAPI(bytes);
    }
}
mac@MacdeMBP asm % javap -v MyMainNew.class
Classfile /Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMainNew.class
  Last modified 2024-1-22; size 349 bytes
  MD5 checksum a1777a658317cd8700e6eab4edb436d6
public class asm.MyMain
  minor version: 0
  major version: 49
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Utf8               asm/MyMain
   #2 = Class              #1             // asm/MyMain
   #3 = Utf8               java/lang/Object
   #4 = Class              #3             // java/lang/Object
   #5 = Utf8               a
   #6 = Utf8               I
   #7 = Utf8               b
   #8 = Utf8               <init>
   #9 = Utf8               ()V
  #10 = NameAndType        #8:#9          // "<init>":()V
  #11 = Methodref          #4.#10         // java/lang/Object."<init>":()V
  #12 = NameAndType        #5:#6          // a:I
  #13 = Fieldref           #2.#12         // asm/MyMain.a:I
  #14 = NameAndType        #7:#6          // b:I
  #15 = Fieldref           #2.#14         // asm/MyMain.b:I
  #16 = Utf8               test1
  #17 = Utf8               test2
  #18 = Utf8               main
  #19 = Utf8               ([Ljava/lang/String;)V
  #20 = Utf8               xyz
  #21 = Utf8               Ljava/lang/String;
  #22 = Utf8               Code
{
  public int a;
    descriptor: I
    flags: ACC_PUBLIC

  public int b;
    descriptor: I
    flags: ACC_PUBLIC

  public java.lang.String xyz;
    descriptor: Ljava/lang/String;
    flags: ACC_PUBLIC

  public asm.MyMain();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=1, args_size=1
         0: aload_0
         1: invokespecial #11                 // Method java/lang/Object."<init>":()V
         4: aload_0
         5: bipush        10
         7: putfield      #13                 // Field a:I
        10: aload_0
        11: bipush        11
        13: putfield      #15                 // Field b:I
        16: return

  public void test1();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=0, locals=1, args_size=1
         0: return

  public void test2();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=0, locals=1, args_size=1
         0: return

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=0, locals=1, args_size=1
         0: return
}
mac@MacdeMBP asm % 

//TreeAPI增加一个属性

package asm;
import org.objectweb.asm.*;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import util.FileUtil;

import java.io.IOException;
import java.util.List;

import static org.objectweb.asm.Opcodes.*;

public class ASMAddFieldClassTest {

//    /**
//     * 方法1,通过core API 增加一个String类型的变量xyz
//     *
//     * @param bytes
//     */
//    public static void editClassInfoByCoreAPI(byte[] bytes) {
//
//        ClassReader classReader = new ClassReader(bytes);
//        ClassWriter classWriter = new ClassWriter(0);
//        ClassVisitor classVisitor = new ClassVisitor(ASM5, classWriter) {
//
//            @Override
//            public void visitEnd() {
//                //todo 我们的目标是增加一个属性,其他都不需要动,所以按照这个思路,其他方法都不需要改动,只要在这个结束方法增加一个属性即可
//                super.visitEnd();
//                FieldVisitor fieldVisitor = super.visitField(ACC_PUBLIC, "xyz", "Ljava/lang/String;", null, null);
//                if(fieldVisitor != null){
//                    fieldVisitor.visitEnd();
//                }
//
//            }
//        };
//
//        classReader.accept(classVisitor, ClassReader.SKIP_DEBUG);
//
//        //拿到修改好的字节码,重新写到一个文件里去
//        byte[] newBytes = classWriter.toByteArray();
//
//        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMainNew.class";
//        FileUtil.writeByteArrayToFile(filePath, newBytes);
//
//    }

    /**
     * 第二种方式,听过TreeAPI来增加字段
     *
     * @param bytes
     */
    public static void editClassInfoByTreeAPI(byte[] bytes) {
        ClassReader classReader = new ClassReader(bytes);
        ClassNode classNode = new ClassNode();
        classReader.accept(classNode, ClassReader.SKIP_DEBUG);

        FieldNode fieldNode = new FieldNode(ACC_PUBLIC|ACC_STATIC, "abc", "Ljava/lang/String;", null, null);

        classNode.fields.add(fieldNode);

        ClassWriter classWriter = new ClassWriter(0);
        classNode.accept(classWriter);

        //拿到修改好的字节码,重新写到一个文件里去
        byte[] newBytes = classWriter.toByteArray();

        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMainTree.class";
        FileUtil.writeByteArrayToFile(filePath, newBytes);
    }


    public static void main(String[] args) throws IOException {
        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm//MyMain.class";
        byte[] bytes = FileUtil.getContent(filePath);
        editClassInfoByTreeAPI(bytes);
    }
}
mac@MacdeMBP asm % ls                       
ASMAddFieldClassTest.class      MyMain.class                    MyMainNew2.class
ASMReadClassTest.class          MyMainNew.class                 MyMainTree.class
mac@MacdeMBP asm % javap -v MyMainTree.class
Classfile /Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMainTree.class
  Last modified 2024-1-22; size 349 bytes
  MD5 checksum c4d1ac0f63f8fe9b91d552e7a6ac1330
public class asm.MyMain
  minor version: 0
  major version: 49
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Utf8               asm/MyMain
   #2 = Class              #1             // asm/MyMain
   #3 = Utf8               java/lang/Object
   #4 = Class              #3             // java/lang/Object
   #5 = Utf8               a
   #6 = Utf8               I
   #7 = Utf8               b
   #8 = Utf8               abc
   #9 = Utf8               Ljava/lang/String;
  #10 = Utf8               <init>
  #11 = Utf8               ()V
  #12 = NameAndType        #10:#11        // "<init>":()V
  #13 = Methodref          #4.#12         // java/lang/Object."<init>":()V
  #14 = NameAndType        #5:#6          // a:I
  #15 = Fieldref           #2.#14         // asm/MyMain.a:I
  #16 = NameAndType        #7:#6          // b:I
  #17 = Fieldref           #2.#16         // asm/MyMain.b:I
  #18 = Utf8               test1
  #19 = Utf8               test2
  #20 = Utf8               main
  #21 = Utf8               ([Ljava/lang/String;)V
  #22 = Utf8               Code
{
  public int a;
    descriptor: I
    flags: ACC_PUBLIC

  public int b;
    descriptor: I
    flags: ACC_PUBLIC

  public static java.lang.String abc;
    descriptor: Ljava/lang/String;
    flags: ACC_PUBLIC, ACC_STATIC

  public asm.MyMain();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=1, args_size=1
         0: aload_0
         1: invokespecial #13                 // Method java/lang/Object."<init>":()V
         4: aload_0
         5: bipush        10
         7: putfield      #15                 // Field a:I
        10: aload_0
        11: bipush        11
        13: putfield      #17                 // Field b:I
        16: return

  public void test1();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=0, locals=1, args_size=1
         0: return

  public void test2();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=0, locals=1, args_size=1
         0: return

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=0, locals=1, args_size=1
         0: return
}
mac@MacdeMBP asm % 

四、使用asm编辑方法实战

添加一个zyx方法:

package asm;

import org.objectweb.asm.*;
import util.FileUtil;

import java.io.IOException;

import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ASM5;

public class ASMEditMethodClassTest {

    /**
     * 增加一个方法
     *
     * @throws IOException
     */

    public static void addMethod(byte[] bytes) {
        ClassReader classReader = new ClassReader(bytes);
        ClassWriter classWriter = new ClassWriter(0);
        ClassVisitor classVisitor = new ClassVisitor(ASM5, classWriter) {
            @Override
            public void visitEnd() {
                super.visitEnd();
                MethodVisitor methodVisitor = super.visitMethod(ACC_PUBLIC, "zyx", "(IILjava/lang/String;)V", null, null);
                if(methodVisitor != null){
                    methodVisitor.visitEnd();
                }
            }
        };

        classReader.accept(classVisitor, ClassReader.SKIP_DEBUG);

        //拿到修改好的字节码,重新写到一个文件里去
        byte[] newBytes = classWriter.toByteArray();

        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMainAddMethod.class";
        FileUtil.writeByteArrayToFile(filePath, newBytes);
    }

    public static void main(String[] args) throws IOException {
        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMain.class";
        byte[] bytes = FileUtil.getContent(filePath);
        addMethod(bytes);
    }
}
mac@MacdeMBP asm % ls                            
ASMAddFieldClassTest.class      ASMEditMethodClassTest.class    MyMain.class                    MyMainNew.class                 MyMainTree.class
ASMEditMethodClassTest$1.class  ASMReadClassTest.class          MyMainAddMethod.class           MyMainNew2.class
mac@MacdeMBP asm % javap -v MyMainAddMethod.class
Classfile /Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMainAddMethod.class
  Last modified 2024-1-22; size 354 bytes
  MD5 checksum 9fdee43198912003ad1896011d11ccc4
public class asm.MyMain
  minor version: 0
  major version: 49
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Utf8               asm/MyMain
   #2 = Class              #1             // asm/MyMain
   #3 = Utf8               java/lang/Object
   #4 = Class              #3             // java/lang/Object
   #5 = Utf8               a
   #6 = Utf8               I
   #7 = Utf8               b
   #8 = Utf8               <init>
   #9 = Utf8               ()V
  #10 = NameAndType        #8:#9          // "<init>":()V
  #11 = Methodref          #4.#10         // java/lang/Object."<init>":()V
  #12 = NameAndType        #5:#6          // a:I
  #13 = Fieldref           #2.#12         // asm/MyMain.a:I
  #14 = NameAndType        #7:#6          // b:I
  #15 = Fieldref           #2.#14         // asm/MyMain.b:I
  #16 = Utf8               test1
  #17 = Utf8               test2
  #18 = Utf8               main
  #19 = Utf8               ([Ljava/lang/String;)V
  #20 = Utf8               zyx
  #21 = Utf8               (IILjava/lang/String;)V
  #22 = Utf8               Code
{
  public int a;
    descriptor: I
    flags: ACC_PUBLIC

  public int b;
    descriptor: I
    flags: ACC_PUBLIC

  public asm.MyMain();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=1, args_size=1
         0: aload_0
         1: invokespecial #11                 // Method java/lang/Object."<init>":()V
         4: aload_0
         5: bipush        10
         7: putfield      #13                 // Field a:I
        10: aload_0
        11: bipush        11
        13: putfield      #15                 // Field b:I
        16: return

  public void test1();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=0, locals=1, args_size=1
         0: return

  public void test2();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=0, locals=1, args_size=1
         0: return

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=0, locals=1, args_size=1
         0: return

  public void zyx(int, int, java.lang.String);
    descriptor: (IILjava/lang/String;)V
    flags: ACC_PUBLIC
}
mac@MacdeMBP asm % 

删除zyx方法:

package asm;

import org.objectweb.asm.*;
import util.FileUtil;

import java.io.IOException;

import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ASM5;

public class ASMEditMethodClassTest {

//    /**
//     * 增加一个方法
//     *
//     * @throws IOException
//     */
//
//    public static void addMethod(byte[] bytes) {
//        ClassReader classReader = new ClassReader(bytes);
//        ClassWriter classWriter = new ClassWriter(0);
//        ClassVisitor classVisitor = new ClassVisitor(ASM5, classWriter) {
//            @Override
//            public void visitEnd() {
//                super.visitEnd();
//                MethodVisitor methodVisitor = super.visitMethod(ACC_PUBLIC, "zyx", "(IILjava/lang/String;)V", null, null);
//                if(methodVisitor != null){
//                    methodVisitor.visitEnd();
//                }
//            }
//        };
//
//        classReader.accept(classVisitor, ClassReader.SKIP_DEBUG);
//
//        //拿到修改好的字节码,重新写到一个文件里去
//        byte[] newBytes = classWriter.toByteArray();
//
//        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMainAddMethod.class";
//        FileUtil.writeByteArrayToFile(filePath, newBytes);
//    }

    /**
     * 删除一个方法
     *
     * @param bytes
     */
    public static void deleteMethod(byte[] bytes) {
        ClassReader classReader = new ClassReader(bytes);
        ClassWriter classWriter = new ClassWriter(0);
        ClassVisitor classVisitor = new ClassVisitor(ASM5, classWriter) {
            @Override
            public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
                super.visit(version, access, name, signature, superName, interfaces);
            }

            @Override
            public void visitSource(String source, String debug) {
                super.visitSource(source, debug);
            }

            @Override
            public void visitOuterClass(String owner, String name, String desc) {
                super.visitOuterClass(owner, name, desc);
            }

            @Override
            public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                return super.visitAnnotation(desc, visible);
            }

            @Override
            public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
                return super.visitTypeAnnotation(typeRef, typePath, desc, visible);
            }

            @Override
            public void visitAttribute(Attribute attr) {
                super.visitAttribute(attr);
            }

            @Override
            public void visitInnerClass(String name, String outerName, String innerName, int access) {
                super.visitInnerClass(name, outerName, innerName, access);
            }

            @Override
            public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
                //如果要删除某个字段返回空
                return super.visitField(access, name, desc, signature, value);
            }

            @Override
            public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
                //如果要删除某个方法返回空
                if ("zyx".equals(name)) {
                    return null;
                }
                return super.visitMethod(access, name, desc, signature, exceptions);
            }

            @Override
            public void visitEnd() {
                //删除一个方法或字段,就不能再写在这里了,可以在过滤前面字段或方法的时候,返回空就可以删除了
                super.visitEnd();
            }
        };
        classReader.accept(classVisitor, ClassReader.SKIP_DEBUG);
        byte[] newBytes = classWriter.toByteArray();
        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMainDeleteMethod.class";
        FileUtil.writeByteArrayToFile(filePath, newBytes);

    }

    public static void main(String[] args) throws IOException {
        String filePath = "/Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMainAddMethod.class";
        byte[] bytes = FileUtil.getContent(filePath);
        deleteMethod(bytes);
    }
}
mac@MacdeMBP asm % ls
ASMAddFieldClassTest.class      ASMEditMethodClassTest.class    MyMain.class                    MyMainDeleteMethod.class        MyMainNew2.class
ASMEditMethodClassTest$1.class  ASMReadClassTest.class          MyMainAddMethod.class           MyMainNew.class                 MyMainTree.class
mac@MacdeMBP asm % javap -v MyMainDeleteMethod.class 
Classfile /Users/mac/IdeaProjects/OOM/JVMSample/target/classes/asm/MyMainDeleteMethod.class
  Last modified 2024-1-22; size 314 bytes
  MD5 checksum b8ea36457b5d3574b2a244b17374421b
public class asm.MyMain
  minor version: 0
  major version: 49
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Utf8               asm/MyMain
   #2 = Class              #1             // asm/MyMain
   #3 = Utf8               java/lang/Object
   #4 = Class              #3             // java/lang/Object
   #5 = Utf8               a
   #6 = Utf8               I
   #7 = Utf8               b
   #8 = Utf8               <init>
   #9 = Utf8               ()V
  #10 = NameAndType        #8:#9          // "<init>":()V
  #11 = Methodref          #4.#10         // java/lang/Object."<init>":()V
  #12 = NameAndType        #5:#6          // a:I
  #13 = Fieldref           #2.#12         // asm/MyMain.a:I
  #14 = NameAndType        #7:#6          // b:I
  #15 = Fieldref           #2.#14         // asm/MyMain.b:I
  #16 = Utf8               test1
  #17 = Utf8               test2
  #18 = Utf8               main
  #19 = Utf8               ([Ljava/lang/String;)V
  #20 = Utf8               Code
{
  public int a;
    descriptor: I
    flags: ACC_PUBLIC

  public int b;
    descriptor: I
    flags: ACC_PUBLIC

  public asm.MyMain();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=1, args_size=1
         0: aload_0
         1: invokespecial #11                 // Method java/lang/Object."<init>":()V
         4: aload_0
         5: bipush        10
         7: putfield      #13                 // Field a:I
        10: aload_0
        11: bipush        11
        13: putfield      #15                 // Field b:I
        16: return

  public void test1();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=0, locals=1, args_size=1
         0: return

  public void test2();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=0, locals=1, args_size=1
         0: return

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=0, locals=1, args_size=1
         0: return
}
mac@MacdeMBP asm % 

五、Javassit介绍与操作字节码案例

package javassist;

import java.io.IOException;

/**
 * 创建类测试
 */
public class JavassistTest {
    public static void main(String[] args) throws CannotCompileException, IOException {
        ClassPool cp = ClassPool.getDefault();
        CtClass ctClass = cp.makeClass("main.java.javassist.HelloJavassist");
        CtField ctField = new CtField(CtClass.intType, "value", ctClass);//ctClass是将属性关联到ctClass
        ctField.setModifiers(Modifier.PUBLIC);
        ctClass.addField(ctField);//这一步真正在ctClass加属性

        CtField ctField2 = new CtField(CtClass.longType, "value2", ctClass);
        ctField2.setModifiers(Modifier.PUBLIC | Modifier.STATIC);
        ctClass.addField(ctField2);//这一步真正在ctClass加属性
        
        ctClass.writeFile("./javassist_gen_file");
    }
}

六、Javassist模拟实现lombok框架

package javassist;

import java.io.IOException;

public class JavassitTest {

    public static void addMethod() throws Exception {
        ClassPool cp = ClassPool.getDefault();
        CtClass ctClass = cp.makeClass("main.java.javassist.HelloJavassist2");

        CtMethod ctMethod = new CtMethod(CtClass.intType,
                "fun",
                new CtClass[]{CtClass.longType, CtClass.charType}, ctClass);
        ctMethod.setModifiers(Modifier.PUBLIC);
        ctClass.addMethod(ctMethod);

        ctClass.writeFile("./javassist_gen_file");
    }

    public static void addMethod2() throws Exception {
        ClassPool cp = ClassPool.getDefault();
        CtClass ctClass = cp.makeClass("main.java.javassist.HelloJavassist2");

        CtField ctField = new CtField(CtClass.intType, "value", ctClass);//ctClass是将属性关联到ctClass
        ctField.setModifiers(Modifier.PRIVATE);
        ctClass.addField(ctField);//这一步真正在ctClass加属性

        CtMethod getMethod = new CtMethod(CtClass.intType,
                "getValue",
                new CtClass[]{}, ctClass);
        getMethod.setModifiers(Modifier.PUBLIC);
        getMethod.setBody(" return this.value;");
        ctClass.addMethod(getMethod);

        CtMethod setMethod = new CtMethod(CtClass.voidType,
                "setValue",
                new CtClass[]{CtClass.intType}, ctClass);
        setMethod.setModifiers(Modifier.PUBLIC);
        setMethod.setBody("this.value = $1;");
        ctClass.addMethod(setMethod);


//        public int add(int a, int b) {
//            return a + b;
//        }
//        CtMethod addMethod = new CtMethod(CtClass.intType,
//                "add",
//                new CtClass[]{CtClass.intType}, ctClass);
//        setMethod.setModifiers(Modifier.PUBLIC);
//        setMethod.setBody("this.value = $1 + $2;");
//        ctClass.addMethod(setMethod);

        ctClass.writeFile("./javassist_gen_file");
    }


    public static void main(String[] args) throws Exception {
        addMethod2();
    }
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package main.java.javassist;

public class HelloJavassist2 {
    private int value;

    public int getValue() {
        return this.value;
    }

    public void setValue(int var1) {
        this.value = var1;
    }

    public HelloJavassist2() {
    }
}

七、反射之一透彻理解反射的作用

通过反射创建对象的多种方式:

package ch14_bytecode_application.class7;

import java.util.Random;

/**
 * 感受反射的作用
 */
public class ReflectionDemo {
    public static void main(String[] args) throws Exception {

//        Student student1 = new Student();
//        student1.getName();
//        System.out.println(student1);
//
//        //反射创建对象方式1:基于已经创建的对象来反射
//        Student student2 = student1.getClass().newInstance();
//        System.out.println(student2);
//
      反射创建对象方式2:  基于类信息来创建Class
//        Class clazz = Student.class;
//        Student student = (Student) clazz.newInstance();
//        System.out.println(student);


        for (int i = 0; i < 5; i++) {
            int num = new Random().nextInt(3);//0,1,2
            String classPath = "";
            switch (num) {
                case 0:
                    classPath = "java.util.Date";
                    break;
                case 1:
                    classPath = "java.lang.Object";
                    break;
                case 2:
                    classPath = "main.java.ch14_bytecode_application.class8.Student";
                    break;
            }

            try {
                Object obj = getInstance(classPath);
                System.out.println(obj);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*
 创建一个指定类的对象。
 classPath:指定类的全类名
  */
    public static Object getInstance(String classPath) throws Exception {
        //反射创建对象方式3:基于已经创建的对象来反射
//        jdbc

        Class clazz = Class.forName(classPath);
        return clazz.newInstance();
    }
}

八、反射之二反射管理类信息案例实战

package class8;

import javassist.Person;

/***
 * 获取class类的四种方式
 */

public class GetClassDemo {
    public static void main(String[] args) throws ClassNotFoundException {
        //方式一:调用运行时类的属性:.class
        Class clazz1 = Person.class;
        System.out.println(clazz1);

        //方式二:通过运行时类的对象,调用getClass()
        Person p1 = new Person();
        Class clazz2 = p1.getClass();

        System.out.println(clazz2);

        //方式三:调用Class的静态方法:forName(String classPath)
        Class clazz3 = Class.forName("main.java.ch14_bytecode_application.class8.Person");
        Class clazz5 = Class.forName("java.lang.String");
        System.out.println(clazz3);
        System.out.println(clazz5);

        System.out.println(clazz1 == clazz2);//true
        System.out.println(clazz1 == clazz3);//true

        //方式四:使用类的加载器:ClassLoader  (了解)
        ClassLoader classLoader = GetClassDemo.class.getClassLoader();
        Class clazz4 = classLoader.loadClass("main.java.ch14_bytecode_application.class8.Person");
        System.out.println(clazz4);
        System.out.println(clazz1 == clazz4);//true
    }
}

package class8;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class FiledMainTest {

    public static void main(String[] args) {
//        test1();
        test2();

    }

    public static void test1() {

        Class clazz = Person.class;

        //获取属性结构
        //getFields():获取当前运行时类及其父类中声明为public访问权限的属性
        Field[] fields = clazz.getFields();
        for (Field f : fields) {
            System.out.println(f);
        }
        System.out.println();

        //getDeclaredFields():获取当前运行时类中声明的所有属性。(不包含父类中声明的属性)
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field f : declaredFields) {
            System.out.println(f);
        }
    }

    //权限修饰符  数据类型 变量名
    public static void test2() {
        Class clazz = Person.class;
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field f : declaredFields) {
            //1.权限修饰符
            int modifier = f.getModifiers();
            System.out.print(Modifier.toString(modifier) + "\t");

            //2.数据类型
            Class type = f.getType();
            System.out.print(type.getName() + "\t");

            //3.变量名
            String fName = f.getName();
            System.out.print(fName);

            System.out.println();
        }
    }
}

test1()执行结果:

/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=55111:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/rt.jar:/Users/mac/IdeaProjects/OOM/JVMSample/target/classes:/Users/mac/repo/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar:/Users/mac/repo/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar class8.FiledMainTest
public int class8.Person.id
public double class8.Creature.weight

private java.lang.String class8.Person.name
int class8.Person.age
public int class8.Person.id

Process finished with exit code 0

test2()执行结果:

/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=55137:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/rt.jar:/Users/mac/IdeaProjects/OOM/JVMSample/target/classes:/Users/mac/repo/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar:/Users/mac/repo/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar class8.FiledMainTest
private	java.lang.String	name
	int	age
public	int	id

Process finished with exit code 0

package main.java.ch14_bytecode_application.class8;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

//获取当前运行时类的方法结构
public class MethodMainTest {

    public static void main(String[] args) {
//        test1();
        test2();

    }


    public static void test1() {

        Class clazz = Person.class;

        //getMethods():获取当前运行时类及其所有父类中声明为public权限的方法
        Method[] methods = clazz.getMethods();
        for (Method m : methods) {
            System.out.println(m);
        }
        System.out.println();
        //getDeclaredMethods():获取当前运行时类中声明的所有方法。(不包含父类中声明的方法)
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method m : declaredMethods) {
            System.out.println(m);
        }
    }
    /*
      @Xxxx
      权限修饰符  返回值类型  方法名(参数类型1 形参名1,...) throws XxxException{}
       */

    public static void test2() {
        Class clazz = Person.class;
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method m : declaredMethods) {
            //1.获取方法声明的注解
            Annotation[] annos = m.getAnnotations();
            for (Annotation a : annos) {
                System.out.println(a);
            }

            //2.权限修饰符
            System.out.print(Modifier.toString(m.getModifiers()) + "\t");

            //3.返回值类型
            System.out.print(m.getReturnType().getName() + "\t");

            //4.方法名
            System.out.print(m.getName());
            System.out.print("(");
            //5.形参列表
            Class[] parameterTypes = m.getParameterTypes();
            if (!(parameterTypes == null && parameterTypes.length == 0)) {
                for (int i = 0; i < parameterTypes.length; i++) {

                    if (i == parameterTypes.length - 1) {
                        System.out.print(parameterTypes[i].getName() + " args_" + i);
                        break;
                    }

                    System.out.print(parameterTypes[i].getName() + " args_" + i + ",");
                }
            }

            System.out.print(")");

            //6.抛出的异常
            Class[] exceptionTypes = m.getExceptionTypes();
            if (exceptionTypes.length > 0) {
                System.out.print("throws ");
                for (int i = 0; i < exceptionTypes.length; i++) {
                    if (i == exceptionTypes.length - 1) {
                        System.out.print(exceptionTypes[i].getName());
                        break;
                    }

                    System.out.print(exceptionTypes[i].getName() + ",");
                }
            }

            System.out.println();
        }

    }
}


test1()执行结果:

/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=55361:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/rt.jar:/Users/mac/IdeaProjects/OOM/JVMSample/target/classes:/Users/mac/repo/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar:/Users/mac/repo/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar class8.MethodMainTest
public void class8.Person.info()
public java.lang.String class8.Person.display(java.lang.String,int) throws java.lang.NullPointerException,java.lang.ClassCastException
public java.lang.String class8.Person.toString()
public int class8.Person.compareTo(java.lang.Object)
public int class8.Person.compareTo(java.lang.String)
public void class8.Creature.eat()
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()

public void class8.Person.info()
public java.lang.String class8.Person.display(java.lang.String,int) throws java.lang.NullPointerException,java.lang.ClassCastException
private java.lang.String class8.Person.show(java.lang.String)
private static void class8.Person.showDesc()
public java.lang.String class8.Person.toString()
public int class8.Person.compareTo(java.lang.Object)
public int class8.Person.compareTo(java.lang.String)

Process finished with exit code 0

test2()执行结果:

/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=55387:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/rt.jar:/Users/mac/IdeaProjects/OOM/JVMSample/target/classes:/Users/mac/repo/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar:/Users/mac/repo/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar class8.MethodMainTest
@class8.MyAnnotation(value=hello)
private	java.lang.String	show(java.lang.String args_0)
public	java.lang.String	display(java.lang.String args_0,int args_1)throws java.lang.NullPointerException,java.lang.ClassCastException
public	void	info()
private static	void	showDesc()
public	java.lang.String	toString()
public volatile	int	compareTo(java.lang.Object args_0)
public	int	compareTo(java.lang.String args_0)

Process finished with exit code 0

九、反射之三反射修改类信息案例实战

通过反射设置和获取对象属性值:

package class9;

public class Person {
    public int id;
    private String name;
    protected int age;


    private static String showDesc() {
        return "aa";
    }

    private String show(String test) {
        return test + " 是一位好老师";
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", id=" + id +
                '}';
    }
}
package class9;

import java.lang.reflect.Field;

/**
 * public : getField() 之后可以直接用反射来set
 * protected :使用getDeclaredField()方法获取,之后可以直接用反射来set
 * private:使用getDeclaredField()方法获取,然后设置权限setAccessible,之后才可以用反射来set
 *
 */

public class ReflectionModifyFiledTest {

    public static void main(String[] args) throws Exception {
//        testField2();
        testField();

    }

    public static void testField2() throws Exception {
        Class clazz = Person.class;

        Person person = (Person) clazz.newInstance();
        Field age = clazz.getDeclaredField("age");
//        age.setAccessible(true);
        age.set(person, 100);

        System.out.println(person);
        System.out.println("---------------------");

        Person person2 = (Person) clazz.newInstance();
        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);
        name.set(person2, "海涛");
        System.out.println(person2);

    }


    /**
     * 修改类的属性信息
     *
     * @throws Exception
     */
    public static void testField() throws Exception {
        Class clazz = Person.class;

        Person person = (Person) clazz.newInstance();
        Field id = clazz.getField("id");
        id.set(person, 100);

        int pId = (Integer) id.get(person);
        System.out.println(pId);
    }


}
/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=63419:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/rt.jar:/Users/mac/IdeaProjects/OOM/JVMSample/target/classes:/Users/mac/repo/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar:/Users/mac/repo/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar class9.ReflectionModifyFiledTest
100

Process finished with exit code 0

通过反射获取对象的所有属性值:

package class9;

import java.lang.reflect.Field;

/**
 * public : getField() 之后可以直接用反射来set
 * protected :使用getDeclaredField()方法获取,之后可以直接用反射来set
 * private:使用getDeclaredField()方法获取,然后设置权限setAccessible,之后才可以用反射来set
 *
 */

public class ReflectionModifyFiledTest {

    public static void main(String[] args) throws Exception {
        testField2();
//        testField();

    }

    public static void testField2() throws Exception {
        Class clazz = Person.class;

        Person person = (Person) clazz.newInstance();
        Field age = clazz.getDeclaredField("age");
//        age.setAccessible(true);
        age.set(person, 100);

        System.out.println(person);
        System.out.println("---------------------");

        Person person2 = (Person) clazz.newInstance();
        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);//正常情况下,通过上面方法,访问私有属性,需要将accessible设置为true,否则会访问不到,报异常
        name.set(person2, "海涛");
        System.out.println(person2);

    }


    /**
     * 修改类的属性信息
     *
     * @throws Exception
     */
    public static void testField() throws Exception {
        Class clazz = Person.class;

        Person person = (Person) clazz.newInstance();
        Field id = clazz.getField("id");
        id.set(person, 100);

        int pId = (Integer) id.get(person);
        System.out.println(pId);
    }


}
/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=49952:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/rt.jar:/Users/mac/IdeaProjects/OOM/JVMSample/target/classes:/Users/mac/repo/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar:/Users/mac/repo/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar class9.ReflectionModifyFiledTest
Person{name='null', age=100, id=0}
---------------------
Person{name='海涛', age=0, id=0}

Process finished with exit code 0

总结:

* public : getField() 之后可以直接用反射来set
* protected :使用getDeclaredField()方法获取,之后可以直接用反射来set
* private:使用getDeclaredField()方法获取,然后设置权限setAccessible,之后才可以用反射来set

十、反射之四通过反射调用类方法实战

package class9;

import java.lang.reflect.Method;

public class ReflectionMethodTest {
    public static void main(String[] args) throws Exception {
        testMethod();
    }

    public static void testMethod() throws Exception {

        Class clazz = Person.class;

        Person person = (Person) clazz.newInstance();

        Method showMethod = clazz.getDeclaredMethod("show", String.class);
        showMethod.setAccessible(true);

        Object value = showMethod.invoke(person, "海涛");
        System.out.println(value);

        Method desc = clazz.getDeclaredMethod("showDesc");
        desc.setAccessible(true);
        Object descValue = desc.invoke(Person.class);
        System.out.println(descValue);


    }


}
/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=59139:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/rt.jar:/Users/mac/IdeaProjects/OOM/JVMSample/target/classes:/Users/mac/repo/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar:/Users/mac/repo/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar class9.A
海涛 是一位好老师
aa

Process finished with exit code 0

十一、代理之一代理思想介绍screenflow

静态代理实现:

业务接口

package class11;

public interface ITicketService {

    //问询
    public void inquire();

    //售票
    public void sellTicket();


}

业务自身接口实现:

package class11;

public class Station implements ITicketService{

    @Override
    public void inquire() {
        System.out.println("海涛老师 问询...");
    }

    @Override
    public void sellTicket() {
        System.out.println("海涛老师 售票.....");
    }





}

代理实现:

package class11;

public class StationProxy implements ITicketService{
    private Station station;

    public StationProxy(Station station){
        this.station = station;
    }

    @Override
    public void inquire() {
        System.out.println("代理人 协助海涛老师问询");
        station.inquire();
        System.out.println("代理人 协助海涛老师问询结束,并做记录");
    }

    @Override
    public void sellTicket() {
        System.out.println("代理人 协助海涛老师售票");
        station.sellTicket();
        System.out.println("代理人 协助海涛老师报销");
    }
}

执行代码:

package class11;

public class MainTest {
    public static void main(String[] args) {
        Station station = new Station();
        ITicketService ticketService = new StationProxy(station);
        ticketService.inquire();

        System.out.println("------------------");

        ticketService.sellTicket();
    }
}

执行结果:

/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=50058:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/rt.jar:/Users/mac/IdeaProjects/OOM/JVMSample/target/classes:/Users/mac/repo/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar:/Users/mac/repo/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar class11.MainTest
代理人 协助海涛老师问询
海涛老师 问询...
代理人 协助海涛老师问询结束,并做记录
------------------
代理人 协助海涛老师售票
海涛老师 售票.....
代理人 协助海涛老师报销

Process finished with exit code 0

十二、代理之二基于JDK实现动态代理实战

业务接口:

package class12.jdkdemp;

public interface ISubject {
    public void rent();

    public void hello(String str);
}

业务实现:

package class12.jdkdemp;

public class SubjectImpl implements ISubject {
    @Override
    public void rent() {
        System.out.println("I want to rent my house");
    }

    @Override
    public void hello(String str) {
        System.out.println("hello: " + str);
    }

}

动态代理实现:

package class12.jdkdemp;

public class SubjectImpl implements ISubject {
    @Override
    public void rent() {
        System.out.println("I want to rent my house");
    }

    @Override
    public void hello(String str) {
        System.out.println("hello: " + str);
    }

}

执行代码:

package class12.jdkdemp;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class MainTest {
    public static void main(String[] args) {
        ISubject subject = new SubjectImpl();
        InvocationHandler handler = new DynamicProxy(subject);

        /**
         * 第一个参数 classLoader - handler的加载器,subject.getClass().getInterfaces() 也是可以的,真正是只传两个加载器
         * 第二个参数 代理的接口
         * 第三个参数 handler
         */
        ISubject subject1 = (ISubject) Proxy.newProxyInstance(
                handler.getClass().getClassLoader(),
                subject.getClass().getInterfaces(),
                handler
        );

        subject1.rent();
    }
}

执行结果:

/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=57555:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/rt.jar:/Users/mac/IdeaProjects/OOM/JVMSample/target/classes:/Users/mac/repo/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar:/Users/mac/repo/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar class12.jdkdemp.MainTest
租房之前。。。
Method public abstract void class12.jdkdemp.ISubject.rent()
I want to rent my house
租到房子。。。

Process finished with exit code 0

缺点:使用基于JDK动态代理,必须有接口,如果没有接口,就无法使用动态代理。

十三、代理之三基于CGlib实现动态代理实战

引入CGLIB:

<dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib-full</artifactId>
      <version>2.0.2</version>
    </dependency>

核心业务类:

package cglib;

public class SubjectClass {
    public void testproxy()
    {
        System.out.println("找房源.....");
    }
}

代理实现类:

package cglib;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class SubjectProxy implements MethodInterceptor {
    @Override
    public Object intercept(Object obj, Method method, Object[] args,
                            MethodProxy methodProxy) throws Throwable {
        System.out.println("房屋中介搜索房源");
        methodProxy.invokeSuper(obj, args);
        System.out.println("房屋中介中介费");
        return null;
    }

}

执行代码:

package cglib;

import net.sf.cglib.proxy.Enhancer;

public class MainTest {
    public static void main(String[] args) {
        SubjectProxy subjectProxy = new SubjectProxy();
        //cglib 中加强器,用来创建动态代理
        Enhancer enhancer = new Enhancer();
        //设置要创建动态代理的类
        enhancer.setSuperclass(SubjectClass.class);
        // 设置回调,这里相当于是对于代理类上所有方法的调用,都会调用CallBack,而Callback则需要实行intercept()方法进行拦截
        enhancer.setCallback(subjectProxy);
        SubjectClass proxy = (SubjectClass) enhancer.create();
        proxy.testproxy();

    }

}

运行结果:

/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=54389:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre/lib/rt.jar:/Users/mac/IdeaProjects/jvm/cglib-test/target/classes:/Users/mac/repo/cglib/cglib-full/2.0.2/cglib-full-2.0.2.jar:/Users/mac/repo/com/alibaba/fastjson/1.2.83/fastjson-1.2.83.jar:/Users/mac/repo/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar cglib.MainTest
房屋中介搜索房源
找房源.....
房屋中介中介费

Process finished with exit code 0

原理:类似子类继承父类,调用子类方法,先执行子类的前置代码,再调用父类的方法,最后再执行子类的后置代码。所以,这里enhancer.setSupeclass(SubjectClass.class)。

十四、字节码技术在FastJson里的应用案例

引入fastjson:

<dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.83</version>
    </dependency>
package class12.fastjson;

import java.util.Date;

public class Person {
    private int age;
    private String name;
    private Date birth;

    public Person(int age, String name, Date birth) {
        this.age = age;
        this.name = name;
        this.birth = birth;
    }

    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;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", birth=" + birth +
                '}';
    }
}
package class12.fastjson;

import com.alibaba.fastjson.JSON;

import java.util.Date;

public class MainTest {
    public static void main(String[] args) {
        Person person = new Person(11, "海涛", new Date());

        String jsonStr = JSON.toJSONString(person);
        System.out.println(jsonStr);

        String str = "{\"age\":22,\"birth\":1696157343030,\"name\":\"海涛老师\"}";
        Person personJson = JSON.parseObject(str, Person.class);
        System.out.println(personJson);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1413960.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

牛客NC16640纪念品分组(C++)

题目链接 实现方法 本题为简单的贪心问题。 将所有纪念品价值排序&#xff1b;使用双指针判断最大和最小的价值之和是否小于上限&#xff0c;若小于上限则取两个&#xff0c;否则取价值较大的一个物品&#xff1b;记录未分组的纪念品数量&#xff0c;若数量为0则跳出循环&…

《PCI Express体系结构导读》随记 —— 第I篇 第3章 PCI总线的数据交换(5)

接前一篇文章&#xff1a;《PCI Express体系结构导读》随记 —— 第I篇 第3章 PCI总线的数据交换&#xff08;4&#xff09; 3.2 PCI设备的数据传递 PCI设备的数据传递使用地址译码方式&#xff0c;当一个存储器读写总线事务到达PCI总线时&#xff0c;在这条总线上的所有PCI设…

Java入门高频考查基础知识7-深入挖掘Java集合框架的奇幻世界2(39题2.8万字参考答案)

Java 集合是 Java 编程中至关重要的组成部分&#xff0c;它为开发者提供了丰富、灵活、高效的数据结构和算法。无论是初学者还是有经验的开发者&#xff0c;在使用 Java 进行编程时都会频繁地接触到集合框架。这篇文章将深入探讨 Java 集合的重要性&#xff0c;以及为什么它对于…

写静态页面——魅族声学_前端页面练习

1、效果: 1、html代码: <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>魅族声学</titl…

STM32单片机项目之多功能智能小车硬件设计

基于STM32单片机多功能智能小车功能说明&#xff1a; TFTLCD显示按键LVGL&#xff08;菜单、小车工作模式选择、设置&#xff09;手机蓝牙遥控模式射频手柄遥控模式5路红外寻迹模式超声波避障模式语音播报低功耗控制 硬件原理图设计 单片机最小系统&#xff1a; 由于要使用…

初识MQRabbitMQ快速入门

一、同步和异步通讯 微服务间通讯有同步和异步两种方式&#xff1a; 同步通讯&#xff1a;就像打电话&#xff0c;需要实时响应。 异步通讯&#xff1a;就像发邮件&#xff0c;不需要马上回复。 两种方式各有优劣&#xff0c;打电话可以立即得到响应&#xff0c;但是你却不能…

项目中日历管理学习使用

一些项目中会有日历或日期设置&#xff0c;最基本的会显示工作日&#xff0c;休息日&#xff0c;节假日等等&#xff0c;下面就是基于项目中的日历管理功能&#xff0c;要显示工作日&#xff0c;休息日&#xff0c;节假日 效果图 获取国家法定节假日工具类 public class Holi…

2024年,我与CSDN的邂逅之旅:一段燃烧激情、成就梦想的博客专家之路

文章目录 初入CSDN知识分享的本质什么有用学什么 成为博客专家的经历成为博客专家有什么好处实际好处隐形好处 今天获得了CSDN认证的博客专家&#xff0c;感觉很开心~分享一下这个始末。分享一下我和CSDN的5年邂逅。 初入CSDN 进入CSDN已经五年了&#xff0c;大一开始写博客&a…

Prometheus 架构全面解析

在本指南中&#xff0c;我们将详细介绍 Prometheus 架构。 Prometheus 是一个用 Golang 编写的开源监控和告警系统&#xff0c;能够收集和处理来自各种目标的指标。您还可以查询、查看、分析指标&#xff0c;并根据阈值收到警报。 此外&#xff0c;在当今世界&#xff0c;可观…

21.云原生之GitLab pipline语法实战(CI基础)

云原生专栏大纲 文章目录 gitlab-ci.yml 介绍GitLab中语法检测gitlab-ci.yml 语法job定义作业before_script和after_scriptstages定义阶段tages指定runnerallow_failure运行失败when控制作业运行retry重试timeout超时parallel并行作业only & exceptrulescache 缓存cache:p…

Windows10系统任务栏变小怎么处理

首先&#xff0c;邮件任务栏&#xff0c;点击任务栏设置&#xff1b; 然后&#xff0c;将小任务栏 使能关闭&#xff08;图中为打开状态&#xff09;&#xff1b; 或者&#xff0c;你也可以取消锁定任务栏&#xff0c;然后在任务栏的边缘&#xff0c;进行上下拉拖动&#xff…

记签名机制

签名过程&#xff1a; 首先将数据源通过摘要算法获取到数字摘要 对数字摘要用私钥进行加密得到签名 将原始消息 以及签名发送给消息接收方 接收方用公钥解密得到数字摘要 用同样的摘要算法将原始消息进行计算 比较得到的数字摘要与解密后的是否一致 Android学习笔记——Androi…

Android源码设计模式解析与实战第2版笔记(二)

第二章 应用最广的模式 — 单例模式 单例模式的定义 确保某一个类只有一个实例&#xff0c;而且自行实例化并向整个系统提供这个实例。 单例模式的使用场景 确保某个类有且只有一个对象的场景&#xff0c;避免产生多个对象消耗过多的资源&#xff0c;或者某种类型的对象只应…

水文模型SWMM与LisFlood耦合(pdf文档、软件见资源)

总技术路线图 INP生成图解 文献&#xff1a;面向服务的Web-SWMM构建研究 regardingINP为ArcGIS Pro项目 1.SWMM模型数据准备与参数设置 1.子汇水区 文件位于&#xff1a;beforeGenerateINP/generateSub.py&#xff08;一级划分&#xff09; 问题&#xff1a; 水文分析阈值划…

85 总结一下最近遇到的一些 jar发布 相关的知识

前言 呵呵 最近有一些构建服务, 发布服务的一些需求 我们这里的服务 一般来说是 java application, spring boot application 针对发布, 当然最好是 增量发布, 尽量的减少需要传递给 发布服务器 的资源的大小 比如 我的这个 java application, 可能会存在很多依赖, 常规…

Arduino开发实例-HTU21D温度和湿度传感器使用

HTU21D温度和湿度传感器使用 文章目录 HTU21D温度和湿度传感器使用1、HTU21D介绍2、硬件接线3、代码实现本文将详细介绍如何使用搭载来自瑞士 MEAS 的低成本、易于使用、高精度的HTU21D数字温度和湿度传感器模块。 1、HTU21D介绍 HTU21D传感器模块尺寸小,几乎可以安装在任何东…

MySQL连表操作之一对多

MySQL连表操作之一对多 目录 引入外键 Navicat创建外键使用外键SQL命令创建外键代码删除外键代码增加外键通过外键进行数据操作 正文 回到顶部 引入 当我们在数据库中创建表的时候&#xff0c;有可能某些列中值内容量很大&#xff0c;而且重复。 例子&#xff1a;创建一个…

磁盘挂载过程

硬盘 - 机械 HDD----便宜---这个&#xff0c;企业中更多- 固态 SSD----快SSD采用电子存储介质进行数据存储和读取的一种技术&#xff0c;突破了传统机械硬盘的性能瓶颈&#xff0c; 拥有极高的存储性能&#xff0c;被认为是存储技术发展的新星。 与传统硬盘相比&#xff0c;SSD…

系统架构演变

1.1系统架构的演变 2008年以后&#xff0c;国内互联网行业飞速发展&#xff0c;我们对软件系统的需求已经不再是过去”能用就行”这种很low的档次了&#xff0c;像抢红包、双十一这样的活动不断逼迫我们去突破软件系统的性能上限&#xff0c;传统的IT企业”能用就行”的开发思…

单片机设计_智能蓝牙电子秤(51单片机、HX711AD)

想要更多项目私wo!!! 一、电路设计 智能蓝牙电子称由51单片机、HX711AD称重模块、HC-05蓝牙模块、LCD1602等电路组成硬件部分,然后上传至APP。 二、运行结果 三、部分代码 #include "main.h" #include "HX711.h" #include "uart.h" #include …