Java class loader的一些总结

时间:2022-01-20 15:42:13

1.  classloader.loadclass 与 class.forName 之间的区别

http://*.com/questions/4285855/difference-betweeen-loading-a-class-using-classloader-and-class-forname

http://www.javaworld.com/javaworld/javaqa/2003-03/01-qa-0314-forname.html

http://www.javalobby.org/java/forums/t18345.html

http://java.sun.com/developer/technicalArticles/Networking/classloaders/

class.forName() 会执行被加载类的静态块,回想加载数据库驱动用的就是class.forName而不是loadclass.


2.  如何调试Java webstart启动的程序?

http://docs.oracle.com/javase/1.5.0/docs/guide/javaws/developersguide/troubleshooting.03.06.html

http://lopica.sourceforge.net/faq.html#debug

start JNLP with debug option

set JAVAWS_TRACE_NATIVE=1
set JAVAWS_VM_ARGS="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8989,server=y,suspend=n"
javaws http://server:port/descriptor.jnlp

1)      double launch problem

download the app.jnlp to local, and start javaws in the same directory with the jnlp file

2)      can’t start listen problem

check your java installation directory, if it contains space, like ‘program files’, you have to start javaws like below script (save as debug.bat i.e.),

java -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8989 -Djnlpx.heapsize=64m,512m -DtrustProxy=true -Xverify:remote -Djava.security.policy="file:D:\Program Files\Java\jdk1.6.0_22\jre\lib\security\javaws.policy" -Xbootclasspath/a:"D:\Program Files\Java\jdk1.6.0_22\jre\lib\deploy.jar";"D:\Program Files\Java\jdk1.6.0_22\jre\lib\javaws.jar";"D:\Program Files\Java\jdk1.6.0_22\jre\lib\plugin.jar" -classpath "D:\Program Files\Java\jdk1.6.0_22\jre\lib\deploy.jar" com.sun.javaws.Main app.jnlp

3. print the classes loaded by a class loader, 使用反射机制获取已经加载了哪些类,

                 Field f;

                  f = ClassLoader.class.getDeclaredField("classes");

                  f.setAccessible(true);

                 

                  System.out.println("classes loaded by URL class loader: ");

                 

                  Vector<Class> classes1 =(Vector<Class>) f.get(Plug.class.getClassLoader());

                 for(Class c : classes1){

                     System.out.println(c);

                  }

4.  URLClassLoader

加载了一个jar包后,是不是改jar包中所有的类都被加载到虚拟机中了呢?不是的。可以参考 http://*.com/questions/7571551/how-to-load-all-classes-of-a-jar-file-at-runtime


5.  Thread.currentThread().setContextClassLoader(classLoader);

当你的程序出现class.forName()抛出ClassNotFound异常时,就可以考虑下当前线程的ContextClassLoader中是不是已经加载了你需要的类了。