使用不同的加载器在JVM中两次加载一个类 [英] Loading a class twice in JVM using different loaders
问题描述
关于类加载的概念,我有一个问题。如何在JVM中两次加载.class文件。我也在写摘录的代码摘录,以完成此操作。.
I have one question regarding concepts of class loading. How to load a .class file twice in JVM. I am also writing an excerpt of code that I have written to accomplish this..
1)加载程序1的代码
1) Loader 1 code
public class MyClassLoader extends ClassLoader {
public MyClassLoader(){
super(MyClassLoader.class.getClassLoader());
}
public Class loadClass(String classname){
try {
return super.loadClass(classname);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
2)加载程序2代码
public class AnotherClassLoader extends ClassLoader {
public AnotherClassLoader(){
super(AnotherClassLoader.class.getClassLoader());
}
public Class loadClass(String classname){
try {
return super.loadClass(classname);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
3)现在,我正在使用这两个不同的类加载器。我想操作classA1 == newClassA应该返回false。这是代码:
3) Now i am loading a class named A using this two different class loaders. I suppose the operation classA1==newClassA should return false. Here is the code:
public static void main(String[] args) {
MyClassLoader loader1 = new MyClassLoader();
AnotherClassLoader newLoader = new AnotherClassLoader();
System.out.println("Load with Custom Class Loader instance");
Class classA1 = loader1.loadClass("com.hitesh.coreJava.A");
System.out.println("Class Loader:::"+classA1.getClassLoader());
Class newClassA = newLoader.loadClass("com.hitesh.coreJava.A");
System.out.println("Class Loader:::"+newClassA.getClassLoader());
System.out.println(classA1==newClassA);
System.out.println(classA1.hashCode() + " , " + newClassA.hashCode());
}
4)执行以上代码的结果:
4) Result of executing above code:
使用自定义类加载器实例加载
类加载器::: sun.misc.Launcher$AppClassLoader@11b86e7
类加载器:: :sun.misc.Launcher$AppClassLoader@11b86e7
true
1641745,1641745
Load with Custom Class Loader instance Class Loader:::sun.misc.Launcher$AppClassLoader@11b86e7 Class Loader:::sun.misc.Launcher$AppClassLoader@11b86e7 true 1641745 , 1641745
请您解释一下
推荐答案
尝试一下
public class Test1 {
static class TestClassLoader1 extends ClassLoader {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (!name.equals("Test1")) {
return super.loadClass(name);
}
try {
InputStream in = ClassLoader.getSystemResourceAsStream("Test1.class");
byte[] a = new byte[10000];
int len = in.read(a);
in.close();
return defineClass(name, a, 0, len);
} catch (IOException e) {
throw new ClassNotFoundException();
}
}
}
public static void main(String[] args) throws Exception {
Class<?> c1 = new TestClassLoader1().loadClass("Test1");
Class<?> c2 = new TestClassLoader1().loadClass("Test1");
System.out.println(c1);
System.out.println(c2);
System.out.println(c1 == c2);
}
}
输出
class Test1
class Test1
false
这篇关于使用不同的加载器在JVM中两次加载一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!