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("没有编译成功!");
            }
        }
}

总结

代码分为三种

源码

字节码

机器码

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


相关文章
|
1天前
|
Java 开发者
Java 面向对象编程实战:从类定义到对象应用,让你成为高手!
【6月更文挑战第15天】在Java中,掌握面向对象编程至关重要。通过创建`Book`类,展示了属性如`title`和`author`,以及构造方法和getter方法。实例化对象如`book1`和`book2`,并访问其属性。进一步扩展类,添加`pages`和`calculateReadingTime`方法,显示了类的可扩展性。在更大规模的项目中,如电商系统,可以定义`Product`、`User`和`Order`类,利用对象表示实体和它们的交互。实践是精通Java OOP的关键,不断学习和应用以提升技能。
|
1天前
|
Java 开发者
为什么 Java 的类和对象如此重要?看完这篇你就懂了!
【6月更文挑战第15天】在Java中,类和对象是核心概念。类作为蓝图定义数据(如角色的名称和健康值)和行为(如`takeDamage`方法),而对象是类的实例,允许交互(如战士受伤)。通过继承,如`Circle`和`Rectangle`扩展`Shape`类,实现多态性,增强代码灵活性。类和对象促进代码组织、复用和可维护性,是高效软件开发的基础。
|
1天前
|
设计模式 Java
一文掌握 Java 面向对象精髓:从类定义到对象实战
【6月更文挑战第15天】Java面向对象编程初学者指南:类是对象模板,如`Person`类含`name`和`age`属性。创建对象用`new`,如`Person person = new Person()`。访问属性如`person.name=&quot;Alice&quot;`,调用方法如`person.sayHello()`。类能继承,如`Student extends Person`。对象间共享数据可传参或共用引用。多态性允许父类引用调用子类方法。注意对象生命周期和内存管理,避免内存泄漏。通过实践和理解这些基础,提升编程技能。
|
1天前
|
Java
深入 Java 面向对象:类的定义,竟然藏着这么多门道!
【6月更文挑战第15天】Java中的类定义是OOP的基础,它封装属性(如Student的name和age)和行为(如study())。简单的类仅触及表面,而复杂的类可模拟真实世界对象的多样性和交互。类还可通过继承扩展,如Student从Person派生,增加特有属性和行为。接口和抽象类等概念进一步增强了灵活性和可扩展性。类定义的深度和广度是构建高效、可维护代码的关键。
|
1天前
|
Java
别再被 Java 类和对象绕晕了!一篇文章让你秒懂!
【6月更文挑战第15天】Java中的类是对象的模板,定义属性(如姓名、年龄)和行为(如走路、说话)。对象是类的实例,有自己的属性值。例如,`Person`类可创建`Person`对象,赋予属性值并调用方法。同样,`Car`类可创建不同品牌的汽车对象,每个对象能加速或刹车。理解类与对象的关系是Java面向对象编程的基础。
|
1天前
|
Java
Java 小白也能看懂!类和对象详解,轻松入门面向对象编程
【6月更文挑战第15天】面向对象编程对新手可能抽象,但理解Java中的类和对象是关键。类是事物模板,如“汽车”类包含属性(颜色、型号、速度)和行为(启动、加速、刹车)。对象是类的实例,像具体的汽车。通过创建对象并调用其方法,可以模拟现实世界的情景。例如,`Car myCar = new Car();`创建了一个汽车对象,之后可设置属性和调用方法。多练习有助于掌握这一概念。
|
1天前
|
Java
Java 面向对象编程:你真的懂类和对象吗?
【6月更文挑战第15天】Java的面向对象编程聚焦于类与对象。类是共享属性和行为的抽象,如`Person`类含名字和年龄。对象是类的具体实例,如`person1`和`person2`各有独特的属性值。设计类时要考虑扩展性,以便适应变化,如添加“性别”属性。对象管理涉及保持其状态和行为的正确性。继承允许类如`Student`扩展`Person`,增加新特性。理解面向对象不仅是创建和使用,更是关于设计和架构的智慧。
|
1天前
|
Java
震惊!原来 Java 的类是这样定义的,你还在等什么?
【6月更文挑战第15天】Java 中的类是对象的蓝图,定义了其属性(如 `name`, `age`)和行为(构造器、方法)。例如,`Student` 类展示了如何通过构造器初始化属性,并通过方法(`getName`, `getAge`)访问这些属性。类的使用促进代码模块化、可维护性和扩展性,允许创建具有相同特征的多个对象,适应不断变化的需求。掌握类定义是提升Java编程能力的基础。
|
2天前
|
安全 Java 数据安全/隐私保护
深入理解java中Unsafe类及其实现原理
深入理解java中Unsafe类及其实现原理
5 0
|
2天前
|
存储 安全 Java
滚雪球学Java(60):深入解析Java中的Vector集合类!
【6月更文挑战第14天】🏆本文收录于「滚雪球学Java」专栏,专业攻坚指数级提升,希望能够助你一臂之力,帮你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!
137 59
滚雪球学Java(60):深入解析Java中的Vector集合类!