类加载器主要分为双亲委派,直接委托。这里我们拓展一个直接委托的例子,读取Jar包动态调用类方法。
/**
* 算法服务
* <p>
* MangoDai
* 2017 08 29 7:45 PM
*/
public class AlgorithmUtils {
private static Logger logger = LoggerFactory.getLogger(AlgorithmUtils.class);
private static final String PRETREATMENTALGORITHMIMPL = "cn.edu.jaxu.bluedot.AlgorithmImpl";
/**
* 使用Jar包来预处理光谱对象
* 地址会自动拼装成绝对路径
* @param algorithmRealPath 算法对象的地址
* @param spectrumfile 光谱对象
* @param isAnalysisAlgorithm 是分析算法吗
* @throws ClassNotFoundException 类没有找到
* @throws InstantiationException 类实例化失败
* @throws IllegalAccessException 实例化没有权限
* @throws IOException Io读写失败
*/
public static JSONArray useJar2PrementSpectrum(String algorithmRealPath, SpectrumFile spectrumfile, boolean isAnalysisAlgorithm)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
URL url1 = new URL("file:" + FileUpload.getBaseABSPath()+ File.separator + algorithmRealPath);
//通过URL得到urlclassLoader加载器
URLClassLoader myClassLoader1 = new URLClassLoader(new URL[]{url1},
Thread.currentThread().getContextClassLoader());
Class myClass1 = myClassLoader1.loadClass(PRETREATMENTALGORITHMIMPL);
try {
String str = null;
if (isAnalysisAlgorithm) {
AnalysisAlgorithm analysisAlgorithm = (AnalysisAlgorithm) myClass1.newInstance();
str = analysisAlgorithm.execute(JSON.toJSONString(spectrumfile.getPoints()), JSON.toJSONString(spectrumfile.getPoints())); // 标准光谱
} else {
PretreatmentAlgorithm pretreatmentAlgorithmImpl = (PretreatmentAlgorithm) myClass1.newInstance();
str = pretreatmentAlgorithmImpl.execute(JSON.toJSONString(spectrumfile.getPoints()));
}
return JSON.parseArray(str);
} catch (PretreatmentAlgorithmException e) {
e.printStackTrace();
logger.error("算法调用失败 : " + e.getMessage());
return null;
}
}
}