java手动加载jar

    @RequestMapping("/testJar")
    public @ResponseBody String exteriorJar(int ys, int csd,int jg,int sf,int yf,int sd){
        String result = "error";
        //从数据库中读取算法类
        String sql = "select EXTERIOR from T_EXTERIOR where id=2";
        InputStream ins = null;
        try{
            Connection con = jdbcTemplate.getDataSource().getConnection();
            Statement ps = con.createStatement();
            ResultSet rs = ps.executeQuery(sql);
            while(rs.next()){
                Blob blob = rs.getBlob("EXTERIOR");
                ins = blob.getBinaryStream();
            }
            File file = new File("test.jar");
            OutputStream os = new FileOutputStream(file);
            byte[] bt = new byte[1024];
            int size = 0;
            while((size=ins.read(bt))!=-1){
                os.write(bt,0,size);
            }
            os.flush();
            os.close();
            ins.close();
            
            URLClassLoader loader = new URLClassLoader(new URL[]{new URL("file:"+file.getAbsolutePath())});
            Class cs = loader.loadClass("com.tf.userApp.bean.Exterior");
            Object obj = cs.newInstance();
            
            Method[] methods = obj.getClass().getMethods();
            for(Method method : methods){
                if(method.getName().equals("add")){
                    Class[] css = method.getParameterTypes();
                    Object[] params = new Object[css.length];
                    params[0] = ys;
                    params[1] = csd;
                    params[2] = jg;
                    params[3] = sf;
                    params[4] = yf;
                    params[5] = sd;
                    /**
                    int index = 0;
                    for(Class cs : css){
                        if(String.class == cs){
                            params[index++] = "String val is :" + index;
                        }
                    }*/
                    Object rt = method.invoke(obj, params);
                    if(rt.getClass() == Integer.class){
                        result = String.valueOf((Integer)rt);
                    }else if(rt.getClass()==String.class){
                        result = (String)rt;
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    } 

 

posted @ 2015-01-27 13:10  自行车上的程序员  阅读(753)  评论(0编辑  收藏  举报