动态加载2

本文介绍了一种通过动态加载jar包来实现特定类的实例化,并解析数据到文件的方法。该方法包括创建输出文件、加载指定jar包中的类、实例化所需对象、解析第三方传来的码流数据并将其写入文件等步骤。

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class LoaderClazz {

 private String traceFile = "";// 写出文件路径
 private int traceType = 0;// 保存码流类型
 private OutputStream outPutStream = null;// 创建全局输出流
 private Object parser = null;// 解析数据对象RespDataParser
 private Object center = null;// MonitorMgrCenter
 private Object adapter = null;// MonitorItemAdapter
 private Object monitorAdapter = null;// BasicMonitorAdapter
 private Object dataStuct = null;// MonitorDataStruct
 private Map<String, Class> classMap = new HashMap<String, Class>(5);// 存放完整class
 private Object monitorFileParser = null;// 初始化调用response.xml消息流 对象(单态)
 private boolean writeHeader = false;

 /**
  * @desc 创建文件
  * @param traceType
  *            码流类型
  * @param jarFiles
  *            动态加载jar
  * @param tracefile
  *            写文件的路径
  * @return 文件创建是否成功? 成功 true: 失败false
  */
 public boolean createTraceFile(int traceType, String[] jarFiles,
   String tracefile) {
  this.traceFile = tracefile;
  this.traceType = traceType;

  /**
   * 1.先加载动态数据 2.解析 3.创建文件
   */

  /***********************************************************************
   * @步骤分解1:动态加载jar
   * @jarFiles:jar文件(绝对路径)
   * @备注:
   *
   **********************************************************************/
  URLClassLoader loader = getLoad(jarFiles);// 返回类加载器
  for (String file : jarFiles) {
   JarFile jar = null;
   try {
    jar = new JarFile(file);
   } catch (IOException e) {
    e.printStackTrace();
   }
   Enumeration<JarEntry> entries = jar.entries();
   String name;
   while (entries.hasMoreElements()) {
    JarEntry entry = entries.nextElement();
    if (isRequireClass(entry.getName())) {

     name = entry.getName();
     System.out.println(name);
     name = name.substring(0, name.length() - 6);
     name = name.replaceAll("/", ".");
     Class<?> clazz = null;
     try {
      clazz = loader.loadClass(name);
      String className = name.substring(
        name.lastIndexOf(".") + 1, name.length());
      classMap.put(className, clazz);
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   }
  }
  try {
   initRequireClass();
  } catch (Exception e1) {
   e1.printStackTrace();
  }
  /** ************************ 初始化response.xml消息流 ******************** */

  this.classParseTree();// 开始加载response.xml消息数据

  /** ************************* 创建文件 ********************************** */
  File file = new File(tracefile);
  if (!file.exists()) {
   try {
    file.createNewFile();
    writeHeader = true;
    return true;
   } catch (IOException e) {
    return false;
   }
  }
  return true;
 }

 // 初始化response.xml消息流
 private void classParseTree() {
  try {
   Method method = monitorFileParser.getClass().getMethod("parseTree",
     null);
   method.invoke(monitorFileParser, null);
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 // 加载需要的类
 @SuppressWarnings( { "rawtypes", "unchecked" })
 private boolean initRequireClass() throws InstantiationException,
   IllegalAccessException, SecurityException, NoSuchMethodException,
   IllegalArgumentException, InvocationTargetException {
  // 获取parser对象
  Class clazz = classMap.get("RespDataParser");// com.swimap.lmt.util.parse.RespDataParser
  parser = clazz.newInstance();

  // 获取center对象
  clazz = classMap.get("MonitorMgrCenter");// com.swimap.lmt.monitor.ctrl.MonitorMgrCenter
  center = clazz.newInstance();

  // 获取monitorFileParser对象
  clazz = classMap.get("MonitorFileParser");// com.swimap.lmt.util.parse.MonitorFileParser
  Method methd = clazz.getMethod("getInstance", null);
  monitorFileParser = methd.invoke(clazz, new Object[] {});

  // 获取adapter对象
  clazz = classMap.get("MonitorItemAdapter");// com.swimap.lmt.monitor.ctrl.MonitorItemAdapter
  Constructor[] con = clazz.getConstructors();
  adapter = con[0].newInstance(traceType);
  Method[] methods = clazz.getMethods();
  for (Method method : methods) {
   if (method.getName().equals("getMonitorAdapter")) {
    monitorAdapter = method
      .invoke(adapter, new Object[] { center });
   }
  }

  // 获取DataStruct对象
  Constructor[] cons = clazz.getConstructors();
  clazz = classMap.get("MonitorDataStruct");// com.swimap.lmt.util.graphics.MonitorDataStruct
  cons = clazz.getConstructors();
  // dataStuct =
  // cons[2].newInstance("dataName","xValue","yValue","rptTime",0,0,0);

  // 判断对象是否为空
  if (parser == null || center == null || adapter == null
    || monitorAdapter == null || monitorFileParser == null
    || dataStuct == null) {
   return false;
  }
  return true;

 }

 private boolean isRequireClass(String name) {
  if (name.contains("RespDataParser.class")
    || name.contains("MonitorMgrCenter.class")
    || name.contains("MonitorItemAdapter.class")
    || name.contains("MonitorFileParser.class")
    || name.contains("MonitorDataStruct.class")) {
   return true;
  }
  return false;
 }

 /**
  * description:根据一个文件(jar),返回一个ClassLoader
  *
  * @param file
  *            *.jar,绝对路径
  * @return 返回一个ClassLoader(类记载器)
  */
 public static URLClassLoader getLoad(String[] files) {
  URL[] url = new URL[files.length];
  for (int i = 0; i < files.length; i++) {
   try {
    url[i] = new URL("file:" + files[i]);
   } catch (MalformedURLException e) {
    e.printStackTrace();
   }
  }
  URLClassLoader loader = new URLClassLoader(url);// 返回类加载器
  return loader;
 }

 /**
  * 自己学习用的,获得一个类加载器。
  *
  * @param jarPath
  * @return
  */
 public static URLClassLoader getLoad(String jarPath) {
  URLClassLoader loader = null;
  try {
   URL url = new URL(jarPath);
   loader = new URLClassLoader(new URL[] { url });
  } catch (MalformedURLException e) {
   e.printStackTrace();
  }
  return loader;
 }

 /**
  * @desc 解析完将结果写入指定路径 文件路径为创建的文件路径
  * @param bin_msg
  *            码流 第三方传过来
  * @return 文件是否写成功 ? 成功 true:失败 false
  */
 public boolean writeTraceFile(byte[] bin_msg) {

  System.out.println("解析消息数据");

  try {
   initRequireClass();
  } catch (Exception e1) {
   e1.printStackTrace();
  }
  ByteBuffer byteBuffer = ByteBuffer.wrap(bin_msg);// 创建ByteBuffer缓冲区
  Object map = parserDataMessage(byteBuffer.array(), traceType);// /////////////////////////////////////////////////////////////////////////////

  Map msgMap = (Map) map;
  StringBuffer stringBuffer = new StringBuffer();
  try {
   Method buildMethod = monitorAdapter.getClass().getMethod(
     "buildDataVector", new Class[] { Map.class });
   Object objectList = buildMethod.invoke(monitorAdapter, msgMap);
   List list = (List) objectList;
   // 下面两行是写dataName,每个文件只写一次
   for (Object obj : list) {
    Method getYMethod = obj.getClass().getMethod("getYValue", null);
    Method getDataMethod = obj.getClass().getMethod("getDataName",
      null);
    Object rptTimeValue = obj.getClass().getMethod("getRptTime",
      null).invoke(obj, null);
    Object yValue = getYMethod.invoke(obj, null);
    Object dataName = getDataMethod.invoke(obj, null);
    if (writeHeader) {
     stringBuffer.append(dataName + "\n" + yValue + ","
       + rptTimeValue + "\n");
    } else {
     stringBuffer.append(yValue + "," + rptTimeValue + "\n");
    }
   }
   if (outPutStream == null) {
    outPutStream = new FileOutputStream(traceFile, true);
   }
   outPutStream.write(stringBuffer.toString().getBytes());
   outPutStream.flush();// 清除缓存
   return true;// 文件写成功
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  }

 }

 /**
  *
  * @param array
  *            码流
  * @param traceType2
  *            码流类型
  * @return
  */
 private Object parserDataMessage(byte[] array, int traceType2) {
  Object result = null;
  try {
   Method method = parser.getClass().getMethod("parseDataMsg",
     new Class[] { byte[].class, int.class });
   result = method.invoke(parser, new Object[] { array, traceType2 });
  } catch (Exception e) {
   e.printStackTrace();
  }
  return result;
 }

 /**
  * @desc 写完文件 将创建的文件进行关闭
  *
  */
 public void closeTraceFile() {
  if (outPutStream != null) {
   try {
    outPutStream.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}

按需引入<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ant Design Vue 纯HTML项目示例</title> <!-- 引入Ant Design Vue的CSS --> <link rel="stylesheet" href="https://unpkg.com/ant-design-vue@3.2.21/dist/antd.css"> <!-- 引入Ant Design X Vue的CSS --> <link rel="stylesheet" href="https://unpkg.com/ant-design-x-vue@1.0.0/dist/antdx.css"> <!-- vue3引入 --> <script src="https://unpkg.com/dayjs/dayjs.min.js"></script> <script src="https://unpkg.com/dayjs/plugin/customParseFormat.js"></script> <script src="https://unpkg.com/dayjs/plugin/weekday.js"></script> <script src="https://unpkg.com/dayjs/plugin/localeData.js"></script> <script src="https://unpkg.com/dayjs/plugin/weekOfYear.js"></script> <script src="https://unpkg.com/dayjs/plugin/weekYear.js"></script> <script src="https://unpkg.com/dayjs/plugin/advancedFormat.js"></script> <script src="https://unpkg.com/dayjs/plugin/quarterOfYear.js"></script> <!-- vue3 --> <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <!-- antdv --> <script src="https://cdn.jsdelivr.net/npm/ant-design-vue@4.2.6/dist/antd.min.js"></script> <!-- antdxv --> <script src="https://cdn.jsdelivr.net/npm/ant-design-x-vue@1.2.7/dist/index.umd.min.js"></script> </head> <body> <div id="app"></div> <script> const { createApp, ref, computed } = Vue; const { Button } = antd; const { Bubble, XProvider } = antdx; createApp({ template: ` <AXProvider :theme="{ algorithm: myThemeAlgorithm, }"> <div :style="{ padding: &#39;24px&#39;, backgroundColor: bgColor, }"> UMD <AXBubble content="hello bubble"></AXBubble> <AButton type="primary" @click="setLightTheme">Light</AButton> <AButton type="primary" @click="setDarkTheme">Dark</AButton> </div> </AXProvider> `, setup() { const { theme } = antd; const bgColor = ref("white"); const myThemeAlgorithm = ref(theme.defaultAlgorithm); const setLightTheme = () => { myThemeAlgorithm.value = theme.defaultAlgorithm; bgColor.value = "white"; }; const setDarkTheme = () => { myThemeAlgorithm.value = theme.darkAlgorithm; bgColor.value = "#141414"; }; return { myThemeAlgorithm, bgColor, setLightTheme, setDarkTheme }; } }) .use(XProvider) .use(Button) .use(Bubble) .mount("#app"); </script> <style> .container { max-width: 1200px; margin: 24px auto; padding: 0 16px; } .search-form { margin-bottom: 24px; padding: 16px; background-color: #f5f5f5; border-radius: 4px; } .user-table { margin-top: 16px; } .mb-6 { margin-bottom: 24px; } .mt-2 { margin-top: 8px; } </style> </body> </html>
07-17
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值