java自动生成类热加载(注册和扫描)

简介: java自动生成类热加载(注册和扫描)

背景

从简单工厂到工厂方法(参考大话设计模式)

将实际的业务封装到了具体的子类中,但是如果无法生成各个子工厂的代码,这种封装还是缺点意思。于是现在想直接根据operation子类生成工厂部分的代码。

实操

1、扫描方式

package PassivehotLoad;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.*;
import java.util.*;
/**
 * @BelongsProject: JAVAtest
 * @BelongsPackage: hotLoad
 * @Author: GuoYuan.Zhao
 * @CreateTime: 2023-03-18  10:17
 * @Description: TODO
 * @Version: 1.0
 */
public class MyManagerHot {
    static String className = "";
    static String operation = "";
    static List<String>allName ;
    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException, IOException {
        //首先去扫描OperationAll包下是不是多了类,如果类变多了,从类中提起关键字 如Add,然后将值赋值给变量,然后按照下面的步骤进行
        String pathPackage = "E:\\zy\\TGB-zgy-2022\\米老师设计模式课相关资料必须留着\\米老师设计模式课小例子\\JAVAtest\\Factory\\src\\main\\java\\MoreAutoFactory\\OperationAll";
        File file = new File(pathPackage);
        if (file.isDirectory()){
            List<String>allNameNew = null;
            File[] files = file.listFiles();
            for (File f : files) {
                String fileName = f.getAbsolutePath();
                if (fileName.endsWith(".java")) {
                    String className = fileName.substring(fileName.indexOf("MoreAutoFactory"), fileName.indexOf(".java"));
                    String replacedName = className.replace("MoreAutoFactory\\OperationAll\\Operation", "");
//                    allNameNew.add(replacedName);
                    create(replacedName);
                    reflect(replacedName);
                }
            }
        }
    }
    public static void create(String className) throws IOException {
        Scanner scanner = new Scanner(System.in);
//        System.out.println("请输入要创建的算法的模式:");
//        className = scanner.nextLine();
        if(className.equals("Add")){
            operation = "+";
        }else if (className.equals("Sub")){
            operation = "-";
        }else if (className.equals("Mul")){
            operation = "*";
        }else if (className.equals("Div")){
            operation = "/";
        }
        String srcOperationCode =
                "package MoreAutoFactory.OperationAll;\n" +
                        "\n" +
                        "\n" +
                        "import MoreAutoFactory.Operation;\n" +
                        "\n" +
                        "public class Operation"+className+" extends Operation {\n" +
                        "    @Override\n" +
                        "    public  double getResult(){\n" +
                        "        double result = 0;\n" +
                        "        result  = getNumberA()"+operation+"getNumberB();\n" +
                        "        return result;\n" +
                        "    }\n" +
                        "\n" +
                        "}";
        //要创建文件的路径
        String path1 = "E:\\zy\\TGB-zgy-2022\\米老师设计模式课相关资料必须留着\\米老师设计模式课小例子\\JAVAtest\\Factory\\src\\main\\java\\MoreAutoFactory\\OperationAll\\Operation"+ className+".java";
        File file1 = new File(path1);
        if (!file1.exists()) {
            if (file1.createNewFile()) {
                System.out.println("新类型算法文件创建成功");
                FileWriter fileWriter = new FileWriter(path1);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(srcOperationCode);
                bufferedWriter.close();
                //编译文件
                Compiler(System.getProperty("user.dir")+"\\Factory\\target\\classes",path1);
            }
        }
        String srcFactoryCode =
                "package MoreAutoFactory.FactoryAll;\n" +
                        "\n" +
                        "import MoreAutoFactory.IFactory;\n" +
                        "import MoreAutoFactory.Operation;\n" +
                        "import MoreAutoFactory.OperationAll.Operation"+className+";\n" +
                        "\n" +
                        "public class "+className+"Factory implements IFactory {\n" +
                        "    @Override\n" +
                        "    public Operation createOperation() {\n" +
                        "        return new Operation"+className+"();\n" +
                        "    }\n" +
                        "}";
        //要创建文件的路径
        String path = "E:\\zy\\TGB-zgy-2022\\米老师设计模式课相关资料必须留着\\米老师设计模式课小例子\\JAVAtest\\Factory\\src\\main\\java\\MoreAutoFactory\\FactoryAll\\" + className + "Factory.java";
        File file = new File(path);
        if (!file.exists()) {
            if (file.createNewFile()) {
                System.out.println("新类型工厂文件创建成功");
                FileWriter fileWriter = new FileWriter(path);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(srcFactoryCode);
                bufferedWriter.close();
                //编译文件
                Compiler(System.getProperty("user.dir")+"\\Factory\\target\\classes",path);
            }
        }
        String srcClientCode =
                "package MoreAutoFactory.ClientAll;\n" +
                        "\n" +
                        "import MoreAutoFactory.FactoryAll."+className+"Factory;\n" +
                        "import MoreAutoFactory.IFactory;\n" +
                        "import MoreAutoFactory.Operation;\n" +
                        "\n" +
                        "public class "+className+"Client {\n" +
                        "  public  void getEndResult() throws Exception {\n" +
                        "      IFactory operFactory = new "+className+"Factory();\n" +
                        "      Operation oper = operFactory.createOperation();\n" +
                        "       oper.setNumberA(2);\n" +
                        "       oper.setNumberB(2);\n" +
                        "       double result = oper.getResult();\n" +
//                        "        System.out.println("+className+");\n" +
                        "        System.out.println(result);\n" +
                        "    }\n" +
                        "}";
        //要创建文件的路径
        String pathClient = "E:\\zy\\TGB-zgy-2022\\米老师设计模式课相关资料必须留着\\米老师设计模式课小例子\\JAVAtest\\Factory\\src\\main\\java\\MoreAutoFactory\\ClientAll\\" + className + "Client.java";
        File fileClient = new File(pathClient);
        if (!fileClient.exists()) {
            if (fileClient.createNewFile()) {
                System.out.println("新类型客户端文件创建成功");
                FileWriter fileWriter = new FileWriter(pathClient);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(srcClientCode);
                bufferedWriter.close();
                //编译文件
                Compiler(System.getProperty("user.dir")+"\\Factory\\target\\classes",pathClient);
            }
        }
    }
    public static void reflect(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
//            String str = "MoreAutoFactory.Client"+className+"Client";
//            System.out.println(str);
        Class classClient = Class.forName("MoreAutoFactory.ClientAll."+className+"Client");
        Object object = classClient.newInstance();
        Method getEndResultMethod = classClient.getMethod("getEndResult");
        getEndResultMethod.invoke(object,null);
    }
    public static void Compiler(String compilerPath,String javaPath){
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        int status = javac.run(null, null, null, "-d",
                compilerPath,javaPath);
        if(status!=0){
            System.out.println("没有编译成功!");
        }
    }
}

2、注册方式

package twoMethodCreateClass.Register;
import hotLoad.BaseManager;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;
/**
 * @BelongsProject: JAVAtest
 * @BelongsPackage: hotLoad
 * @Author: GuoYuan.Zhao
 * @CreateTime: 2023-03-18  10:17
 * @Description: TODO
 * @Version: 1.0
 */
public class MyManagerHot {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        create();
        reflect();
    }
        static String className = "";
        static String operation = "";
    public static void create() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要创建的算法的模式:");
        className = scanner.nextLine();
        if(className.equals("Add")){
            operation = "+";
        }else if (className.equals("Sub")){
            operation = "-";
        }else if (className.equals("Mul")){
            operation = "*";
        }else if (className.equals("Div")){
            operation = "/";
        }
        String srcOperationCode =
                "package MoreAutoFactory.OperationAll;\n" +
                        "\n" +
                        "\n" +
                        "import MoreAutoFactory.Operation;\n" +
                        "\n" +
                        "public class Operation"+className+" extends Operation {\n" +
                        "    @Override\n" +
                        "    public  double getResult(){\n" +
                        "        double result = 0;\n" +
                        "        result  = getNumberA()"+operation+"getNumberB();\n" +
                        "        return result;\n" +
                        "    }\n" +
                        "\n" +
                        "}";
        //要创建文件的路径
        String path1 = "E:\\zy\\TGB-zgy-2022\\米老师设计模式课相关资料必须留着\\米老师设计模式课小例子\\JAVAtest\\Factory\\src\\main\\java\\MoreAutoFactory\\OperationAll\\Operation"+ className+".java";
        File file1 = new File(path1);
        if (!file1.exists()) {
            if (file1.createNewFile()) {
                System.out.println("新类型算法文件创建成功");
                FileWriter fileWriter = new FileWriter(path1);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(srcOperationCode);
                bufferedWriter.close();
                //编译文件
                Compiler(System.getProperty("user.dir")+"\\Factory\\target\\classes",path1);
            }
        }
        String srcFactoryCode =
                "package MoreAutoFactory.FactoryAll;\n" +
                        "\n" +
                        "import MoreAutoFactory.IFactory;\n" +
                        "import MoreAutoFactory.Operation;\n" +
                        "import MoreAutoFactory.OperationAll.Operation"+className+";\n" +
                        "\n" +
                        "public class "+className+"Factory implements IFactory {\n" +
                        "    @Override\n" +
                        "    public Operation createOperation() {\n" +
                        "        return new Operation"+className+"();\n" +
                        "    }\n" +
                        "}";
        //要创建文件的路径
        String path = "E:\\zy\\TGB-zgy-2022\\米老师设计模式课相关资料必须留着\\米老师设计模式课小例子\\JAVAtest\\Factory\\src\\main\\java\\MoreAutoFactory\\FactoryAll\\" + className + "Factory.java";
        File file = new File(path);
        if (!file.exists()) {
            if (file.createNewFile()) {
                System.out.println("新类型工厂文件创建成功");
                FileWriter fileWriter = new FileWriter(path);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(srcFactoryCode);
                bufferedWriter.close();
                //编译文件
                Compiler(System.getProperty("user.dir")+"\\Factory\\target\\classes",path);
            }
        }
        String srcClientCode =
                "package MoreAutoFactory.ClientAll;\n" +
                        "\n" +
                        "import MoreAutoFactory.FactoryAll."+className+"Factory;\n" +
                        "import MoreAutoFactory.IFactory;\n" +
                        "import MoreAutoFactory.Operation;\n" +
                        "\n" +
                        "public class "+className+"Client {\n" +
                        "  public  void getEndResult() throws Exception {\n" +
                        "      IFactory operFactory = new "+className+"Factory();\n" +
                        "      Operation oper = operFactory.createOperation();\n" +
                        "       oper.setNumberA(2);\n" +
                        "       oper.setNumberB(2);\n" +
                        "       double result = oper.getResult();\n" +
                        "        System.out.println(result);\n" +
                        "    }\n" +
                        "}";
        //要创建文件的路径
        String pathClient = "E:\\zy\\TGB-zgy-2022\\米老师设计模式课相关资料必须留着\\米老师设计模式课小例子\\JAVAtest\\Factory\\src\\main\\java\\MoreAutoFactory\\ClientAll\\" + className + "Client.java";
        File fileClient = new File(pathClient);
        if (!fileClient.exists()) {
            if (fileClient.createNewFile()) {
                System.out.println("新类型客户端文件创建成功");
                FileWriter fileWriter = new FileWriter(pathClient);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(srcClientCode);
                bufferedWriter.close();
                //编译文件
                Compiler(System.getProperty("user.dir")+"\\Factory\\target\\classes",pathClient);
            }
        }
    }
        public static void reflect() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
//            String str = "MoreAutoFactory.Client"+className+"Client";
//            System.out.println(str);
            Class classClient = Class.forName("MoreAutoFactory.ClientAll."+className+"Client");
            Object object = classClient.newInstance();
            Method getEndResultMethod = classClient.getMethod("getEndResult");
            getEndResultMethod.invoke(object,null);
        }
        public static void Compiler(String compilerPath,String javaPath){
            JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
            int status = javac.run(null, null, null, "-d",
 compilerPath,javaPath);
            if(status!=0){
                System.out.println("没有编译成功!");
            }
        }
}

总结

代码分为三种

源码

字节码

机器码

我们可以通过改变源码的方式去操纵机器码,这也是实现自动化的关键


相关文章
|
14天前
|
存储 安全 Java
java.util的Collections类
Collections 类位于 java.util 包下,提供了许多有用的对象和方法,来简化java中集合的创建、处理和多线程管理。掌握此类将非常有助于提升开发效率和维护代码的简洁性,同时对于程序的稳定性和安全性有大有帮助。
37 17
|
6天前
|
安全 Java
Java多线程集合类
本文介绍了Java中线程安全的问题及解决方案。通过示例代码展示了使用`CopyOnWriteArrayList`、`CopyOnWriteArraySet`和`ConcurrentHashMap`来解决多线程环境下集合操作的线程安全问题。这些类通过不同的机制确保了线程安全,提高了并发性能。
|
10天前
|
存储 Java 程序员
Java基础的灵魂——Object类方法详解(社招面试不踩坑)
本文介绍了Java中`Object`类的几个重要方法,包括`toString`、`equals`、`hashCode`、`finalize`、`clone`、`getClass`、`notify`和`wait`。这些方法是面试中的常考点,掌握它们有助于理解Java对象的行为和实现多线程编程。作者通过具体示例和应用场景,详细解析了每个方法的作用和重写技巧,帮助读者更好地应对面试和技术开发。
50 4
|
11天前
|
Java 编译器 开发者
Java异常处理的最佳实践,涵盖理解异常类体系、选择合适的异常类型、提供详细异常信息、合理使用try-catch和finally语句、使用try-with-resources、记录异常信息等方面
本文探讨了Java异常处理的最佳实践,涵盖理解异常类体系、选择合适的异常类型、提供详细异常信息、合理使用try-catch和finally语句、使用try-with-resources、记录异常信息等方面,帮助开发者提高代码质量和程序的健壮性。
26 2
|
15天前
|
存储 安全 Java
如何保证 Java 类文件的安全性?
Java类文件的安全性可以通过多种方式保障,如使用数字签名验证类文件的完整性和来源,利用安全管理器和安全策略限制类文件的权限,以及通过加密技术保护类文件在传输过程中的安全。
|
19天前
|
Java 数据格式 索引
使用 Java 字节码工具检查类文件完整性的原理是什么
Java字节码工具通过解析和分析类文件的字节码,检查其结构和内容是否符合Java虚拟机规范,确保类文件的完整性和合法性,防止恶意代码或损坏的类文件影响程序运行。
|
19天前
|
Java API Maven
如何使用 Java 字节码工具检查类文件的完整性
本文介绍如何利用Java字节码工具来检测类文件的完整性和有效性,确保类文件未被篡改或损坏,适用于开发和维护阶段的代码质量控制。
|
19天前
|
存储 Java 编译器
java wrapper是什么类
【10月更文挑战第16天】
22 3
|
22天前
|
Java 程序员 测试技术
Java|让 JUnit4 测试类自动注入 logger 和被测 Service
本文介绍如何通过自定义 IDEA 的 JUnit4 Test Class 模板,实现生成测试类时自动注入 logger 和被测 Service。
21 5
|
22天前
|
Java
在Java多线程编程中,实现Runnable接口通常优于继承Thread类
【10月更文挑战第20天】在Java多线程编程中,实现Runnable接口通常优于继承Thread类。原因包括:1) Java只支持单继承,实现接口不受此限制;2) Runnable接口便于代码复用和线程池管理;3) 分离任务与线程,提高灵活性。因此,实现Runnable接口是更佳选择。
30 2