Java-类加载器面试

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/oz965557340/article/details/79450237

类加载器主要分为双亲委派直接委托。这里我们拓展一个直接委托的例子,读取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;
        }
    }
}
展开阅读全文

没有更多推荐了,返回首页