Java-类加载器面试

类加载器主要分为双亲委派直接委托。这里我们拓展一个直接委托的例子,读取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;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值