zoukankan      html  css  js  c++  java
  • java 动态生成类再编译最后代理

    package spring.vhostall.com.proxy;
    
    public interface Store {
        public void sell();
    }
    
    --------------------------------------------
    package spring.vhostall.com.proxy;
    
    public class Supermarket implements Store {
    
        @Override
        public void sell() {
            System.out.println("sel in supermarket.....");
        }
    }
    
    --------------------------------------------
    package spring.vhostall.com.proxy;
    
    import java.io.File;
    import java.io.FileWriter;
    import java.lang.reflect.Constructor;
    import java.net.URL;
    import java.net.URLClassLoader;
    
    import javax.tools.JavaCompiler;
    import javax.tools.StandardJavaFileManager;
    import javax.tools.ToolProvider;
    
    public class Test {
        public static void main(String[] args) throws Exception {
            String rt = "
    ";
            StringBuilder source = new StringBuilder();
            source.append("package spring.vhostall.com.proxy;" + rt + rt);
            source.append("public class Dealer implements Store" + " {" + rt);
            source.append("    private Store s;" + rt + rt);
            source.append("    public Dealer(Store s) {" + rt);
            source.append("        this.s = s;" + rt);
            source.append("    }" + rt + rt);
            source.append("    public void sell()" + " {" + rt);
            source.append("        System.out.println("price markup....");" + rt);
            source.append("        s.sell();" + rt);
            source.append("    }" + rt);
            source.append("}");
    
            String fileName = System.getProperty("user.dir")// 获取到项目的根路径
                    + "/src/spring/vhostall/com/proxy/Dealer.java";
            File f = new File(fileName);
            FileWriter fw = new FileWriter(f);
            fw.write(source.toString());
            fw.flush();
            fw.close();// 这里只是产生一个JAVA文件,简单的IO操作
    
            // compile下面开始编译这个Store.java
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            URL[] urls = new URL[] { new URL("file:/"
                    + System.getProperty("user.dir") + "/src") };
            URLClassLoader ul = new URLClassLoader(urls);
            Class c = ul.loadClass("spring.vhostall.com.proxy.Dealer");
    
            // 客户端调用
    
            Constructor ctr = c.getConstructor(Store.class);
            Store s = (Store) ctr.newInstance(new Supermarket());// 这里看到,这个我们这个代理类必须实现Store的原因
            s.sell();
        }
    }
  • 相关阅读:
    LINUX系统运行查看
    MySQL数据库中tinyint类型字段读取数据为true和false (MySQL的boolean和tinyint(1))
    mysql DATE_FORMAT 年月日时分秒格式化
    fastJson泛型如何转换
    查找java程序进程快速指令jps
    vim快捷键
    mysql全库搜索指定字符串
    mysql一次性删除所有表而不删除数据库
    一键安装Docker图形化管理界面-Shipyard
    hadoop性能测试
  • 原文地址:https://www.cnblogs.com/sprinng/p/4432797.html
Copyright © 2011-2022 走看看