要求是:
自己继承Classloader。。实现一个Myclassloader。
然后创建两个loader对象,分别加载同一个类。
然后再分别通过loader对象创建两个实例。然后把所有涉及的对象的hashcode都输出出来。
我的代码如下: MyClassLoader ml = new MyClassLoader();
MyClassLoader ml2 = new MyClassLoader();
Class c1 = ml.loadClass("TestClass");
Class c2 = ml2.loadClass("TestClass");
TestClass tc1 = (TestClass) c1.newInstance();
TestClass tc2 = (TestClass) c2.newInstance();
System.out.println("TestClass[" + c1.hashCode()
+ "] loaded by MyClassLoader[" + ml.hashCode() + "]");
System.out.println("TestClass[" + c2.hashCode()
+ "] loaded by MyClassLoader[" + ml2.hashCode() + "]");
System.out.println("Object 1 [" + tc1.hashCode()
+ "] is instance of TestClass[" + c1.hashCode() + "]");
System.out.println("Object 2 [" + tc2.hashCode()
+ "] is instance of TestClass[" + c2.hashCode() + "]");
System.out.println(tc1.equals(tc2));
Myclassloader里我什么都没做,只是继承一下。
老师给了一个输出例子的截图,在他截图上c1和c2的hashcode()结果不一样。而我怎么想都想不开他怎么做到的。虽然他给的例子是继承URLClassLoader,难道和这个有关?附我的输出结果:
TestClass[1414159026] loaded by MyClassLoader[1021653256]
TestClass[1414159026] loaded by MyClassLoader[1794515827]
Object 1 [1167165921] is instance of TestClass[1414159026]
Object 2 [1442002549] is instance of TestClass[1414159026]
要使得hashcode不一样就需要创建新对象吧,就是新开辟内存空间。而 ml.loadClass("TestClass");这个操作似乎没有这个效果。

解决方案 »

  1.   

    hashCode() 底层代码是什么啊?
      

  2.   

    主要原因是这个,
    TestClass tc1 = (TestClass) c1.newInstance();
    TestClass tc2 = (TestClass) c2.newInstance();
    这是通过反射来创建了两个TestClass的对象 tc1和tc2,所以tc1和tc2的hashcode是不一样的但是你可能会疑惑,那么c1和c2的hashcode为什么又是一样的呢?
    Class c1 = ml.loadClass("TestClass");
    Class c2 = ml2.loadClass("TestClass");
    因为每个对象的class只有一个嘛,学过java的人都知道,所以c1和c2指定的class都是同一个,所以他们的hashcode是一样的。
      

  3.   

    楼主你的代码没有问题
    c1和c2 是同一个对象,jvm加载类时会判断当前类是否加载 加载了话 直接返回引用 这在jdk上有说明,
    然后就是c1和c2 创建的实例tc1 和tc2 他们是同一个对象新创建的两个对象 hashcode当然不一样  所以楼主的结果是正确的