"
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 { //测试1 Object obj2 = classLoader("com.myweb.reflect.classloader.ClassLoaderTest"); System.out.println(obj2.getClass()); System.out.println(obj2 instanceof com.myweb.reflect.classloader.ClassLoaderTest);
//测试2
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();
}
}
};
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.ClassLoaderTest
true
class java.lang.Class
false
为什么两段相同的代码,只是一个单独提取出来,输出就不一样了呢?
"
你确定是两段相同的代码吗?
第一个代码段里面有多一句return (T) myClassLoader.loadClass(className).newInstance();
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。