关于JAVA类加载器。
问题描述
public static <T> T classLoader(String className) throws Exception {ClassLoader myClassLoader = new ClassLoader() { @Override protected Class<?> findClass(String name) throws ClassNotFoundException {try { //获取类文件名 String fileName = name.substring(name.lastIndexOf('.') + 1) + '.class'; InputStream inputStream = getClass().getResourceAsStream(fileName); if (inputStream == null) {return super.findClass(fileName); } byte[] bytes = new byte[inputStream.available()]; inputStream.close(); return defineClass(name, bytes, 0, bytes.length);} catch (IOException e) { throw new ClassNotFoundException();} }};return (T) myClassLoader.loadClass(className).newInstance(); }public static void main(String[] args) throws Exception {//测试1Object obj2 = classLoader('com.myweb.reflect.classloader.ClassLoaderTest');System.out.println(obj2.getClass());System.out.println(obj2 instanceof com.myweb.reflect.classloader.ClassLoaderTest);//测试2ClassLoader myClassLoader = new ClassLoader() { @Override protected Class<?> findClass(String name) throws ClassNotFoundException {try { //获取类文件名 String fileName = name.substring(name.lastIndexOf('.') + 1) + '.class'; InputStream inputStream = getClass().getResourceAsStream(fileName); if (inputStream == null) {return super.findClass(fileName); } byte[] bytes = new byte[inputStream.available()]; inputStream.close(); return defineClass(name, bytes, 0, bytes.length);} catch (IOException e) { throw new ClassNotFoundException();} }};Object obj3 = myClassLoader.loadClass('com.myweb.reflect.classloader.ClassLoaderTest');System.out.println(obj3.getClass());System.out.println(obj3 instanceof com.myweb.reflect.classloader.ClassLoaderTest);}
输出:class com.myweb.reflect.classloader.ClassLoaderTesttrueclass java.lang.Classfalse
为什么两段相同的代码,只是一个单独提取出来,输出就不一样了呢?
问题解答
回答1:你确定是两段相同的代码吗?第一个代码段里面有多一句return (T) myClassLoader.loadClass(className).newInstance();
相关文章:
1. 在应用配置文件 app.php 中找不到’route_check_cache’配置项2. 在mac下出现了两个docker环境3. PHP类属性声明?4. win下面的cmder中的vim . 中文乱码. 试了百度上的各种解决方式.. 还是没弄好5. pdo 写入到数据库的内容为中文的时候写入乱码6. html按键开关如何提交我想需要的值到数据库7. PHPExcel表格导入数据库怎么导入8. win10系统 php安装swoole扩展9. html5 - 两个宽高一样的盒子重叠后旋转一定角度,为什么会看到下面的盒子10. html - 关于bootstrap中container、row、col的应用
