You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Loader.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999-2004 Shigeru Chiba. All Rights Reserved.
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. Alternatively, the contents of this file may be used under
  8. * the terms of the GNU Lesser General Public License Version 2.1 or later.
  9. *
  10. * Software distributed under the License is distributed on an "AS IS" basis,
  11. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12. * for the specific language governing rights and limitations under the
  13. * License.
  14. */
  15. package javassist;
  16. import java.io.*;
  17. import java.util.Hashtable;
  18. import java.util.Vector;
  19. /**
  20. * The class loader for Javassist.
  21. *
  22. * <p>This is a sample class loader using <code>ClassPool</code>.
  23. * Unlike a regular class loader, this class loader obtains bytecode
  24. * from a <code>ClassPool</code>.
  25. *
  26. * <p>Note that Javassist can be used without this class loader; programmers
  27. * can define their own versions of class loader. They can run
  28. * a program even without any user-defined class loader if that program
  29. * is statically translated with Javassist.
  30. * This class loader is just provided as a utility class.
  31. *
  32. * <p>Suppose that an instance of <code>MyTranslator</code> implementing
  33. * the interface <code>Translator</code> is responsible for modifying
  34. * class files.
  35. * The startup program of an application using <code>MyTranslator</code>
  36. * should be something like this:
  37. *
  38. * <ul><pre>
  39. * import javassist.*;
  40. *
  41. * public class Main {
  42. * public static void main(String[] args) throws Throwable {
  43. * MyTranslator myTrans = new MyTranslator();
  44. * ClassPool cp = ClassPool.getDefault();
  45. * Loader cl = new Loader(cp);
  46. * cl.addTranslator(cp, myTrans);
  47. * cl.run("MyApp", args);
  48. * }
  49. * }
  50. * </pre></ul>
  51. *
  52. * <p>Class <code>MyApp</code> is the main program of the application.
  53. *
  54. * <p>This program should be executed as follows:
  55. *
  56. * <ul><pre>
  57. * % java Main <i>arg1</i> <i>arg2</i>...
  58. * </pre></ul>
  59. *
  60. * <p>It modifies the class <code>MyApp</code> with a <code>MyTranslator</code>
  61. * object before the JVM loads it.
  62. * Then it calls <code>main()</code> in <code>MyApp</code> with arguments
  63. * <i>arg1</i>, <i>arg2</i>, ...
  64. *
  65. * <p>This program execution is equivalent to:
  66. *
  67. * <ul><pre>
  68. * % java MyApp <i>arg1</i> <i>arg2</i>...
  69. * </pre></ul>
  70. *
  71. * <p>except that classes are translated by <code>MyTranslator</code>
  72. * at load time.
  73. *
  74. * <p>If only a particular class must be modified when it is loaded,
  75. * the startup program can be simpler; <code>MyTranslator</code> is
  76. * unnecessary. For example, if only a class <code>test.Rectangle</code>
  77. * is modified, the <code>main()</code> method above will be the following:
  78. *
  79. * <ul><pre>
  80. * ClassPool cp = ClassPool.getDefault();
  81. * Loader cl = new Loader(cp);
  82. * CtClass ct = cp.get("test.Rectangle");
  83. * ct.setSuperclass(cp.get("test.Point"));
  84. * cl.run("MyApp", args);</pre></ul>
  85. *
  86. * <p>This program changes the super class of the <code>test.Rectangle</code>
  87. * class.
  88. *
  89. * <p><b>Note 1:</b>
  90. *
  91. * <p>This class loader does not allow the users to intercept the loading
  92. * of <code>java.*</code> and <code>javax.*</code> classes unless
  93. * <code>Loader.doDelegation</code> is <code>false</code>. Also see
  94. * Note 2.
  95. *
  96. * <p><b>Note 2:</b>
  97. *
  98. * <p>If classes are loaded with different class loaders, they belong to
  99. * separate name spaces. If class <code>C</code> is loaded by a class
  100. * loader <code>CL</code>, all classes that the class <code>C</code>
  101. * refers to are also loaded by <code>CL</code>. However, if <code>CL</code>
  102. * delegates the loading of the class <code>C</code> to <code>CL'</code>,
  103. * then those classes that the class <code>C</code> refers to
  104. * are loaded by a parent class loader <code>CL'</code>
  105. * instead of <code>CL</code>.
  106. *
  107. * <p>If an object of class <code>C</code> is assigned
  108. * to a variable of class <code>C</code> belonging to a different name
  109. * space, then a <code>ClassCastException</code> is thrown.
  110. *
  111. * <p>Because of the fact above, this loader delegates only the loading of
  112. * <code>javassist.Loader</code>
  113. * and classes included in package <code>java.*</code> and
  114. * <code>javax.*</code> to the parent class
  115. * loader. Other classes are directly loaded by this loader.
  116. *
  117. * <p>For example, suppose that <code>java.lang.String</code> would be loaded
  118. * by this loader while <code>java.io.File</code> is loaded by the parent
  119. * class loader. If the constructor of <code>java.io.File</code> is called
  120. * with an instance of <code>java.lang.String</code>, then it may throw
  121. * an exception since it accepts an instance of only the
  122. * <code>java.lang.String</code> loaded by the parent class loader.
  123. *
  124. * @see javassist.ClassPool
  125. * @see javassist.Translator
  126. */
  127. public class Loader extends ClassLoader {
  128. private Hashtable notDefinedHere; // must be atomic.
  129. private Vector notDefinedPackages; // must be atomic.
  130. private ClassPool source;
  131. private Translator translator;
  132. /**
  133. * Specifies the algorithm of class loading.
  134. *
  135. * <p>This class loader uses the parent class loader for
  136. * <code>java.*</code> and <code>javax.*</code> classes.
  137. * If this variable <code>doDelegation</code>
  138. * is <code>false</code>, this class loader does not delegate those
  139. * classes to the parent class loader.
  140. *
  141. * <p>The default value is <code>true</code>.
  142. */
  143. public boolean doDelegation = true;
  144. /**
  145. * Creates a new class loader.
  146. */
  147. public Loader() {
  148. this(null);
  149. }
  150. /**
  151. * Creates a new class loader.
  152. *
  153. * @param cp the source of class files.
  154. */
  155. public Loader(ClassPool cp) {
  156. init(cp);
  157. }
  158. /**
  159. * Creates a new class loader
  160. * using the specified parent class loader for delegation.
  161. *
  162. * @param parent the parent class loader.
  163. * @param cp the source of class files.
  164. */
  165. public Loader(ClassLoader parent, ClassPool cp) {
  166. super(parent);
  167. init(cp);
  168. }
  169. private void init(ClassPool cp) {
  170. notDefinedHere = new Hashtable();
  171. notDefinedPackages = new Vector();
  172. source = cp;
  173. translator = null;
  174. delegateLoadingOf("javassist.Loader");
  175. }
  176. /**
  177. * Records a class so that the loading of that class is delegated
  178. * to the parent class loader.
  179. *
  180. * <p>If the given class name ends with <code>.</code> (dot), then
  181. * that name is interpreted as a package name. All the classes
  182. * in that package and the sub packages are delegated.
  183. */
  184. public void delegateLoadingOf(String classname) {
  185. if (classname.endsWith("."))
  186. notDefinedPackages.addElement(classname);
  187. else
  188. notDefinedHere.put(classname, this);
  189. }
  190. /**
  191. * Sets the soruce <code>ClassPool</code>.
  192. */
  193. public void setClassPool(ClassPool cp) {
  194. source = cp;
  195. }
  196. /**
  197. * Adds a translator, which is called whenever a class is loaded.
  198. *
  199. * @param cp the <code>ClassPool</code> object for obtaining
  200. * a class file.
  201. * @param t a translator.
  202. * @throws NotFoundException if <code>t.start()</code> throws an exception.
  203. * @throws CannotCompileException if <code>t.start()</code> throws an exception.
  204. */
  205. public void addTranslator(ClassPool cp, Translator t)
  206. throws NotFoundException, CannotCompileException {
  207. source = cp;
  208. translator = t;
  209. t.start(cp);
  210. }
  211. /**
  212. * Loads a class with an instance of <code>Loader</code>
  213. * and calls <code>main()</code> of that class.
  214. *
  215. * <p>This method calls <code>run()</code>.
  216. *
  217. * @param args command line parameters.
  218. * <ul>
  219. * <code>args[0]</code> is the class name to be loaded.
  220. * <br><code>args[1..n]</code> are parameters passed
  221. * to the target <code>main()</code>.
  222. * </ul>
  223. *
  224. * @see javassist.Loader#run(String[])
  225. */
  226. public static void main(String[] args) throws Throwable {
  227. Loader cl = new Loader();
  228. cl.run(args);
  229. }
  230. /**
  231. * Loads a class and calls <code>main()</code> in that class.
  232. *
  233. * @param args command line parameters.
  234. * <ul>
  235. * <code>args[0]</code> is the class name to be loaded.
  236. * <br><code>args[1..n]</code> are parameters passed
  237. * to the target <code>main()</code>.
  238. * </ul>
  239. */
  240. public void run(String[] args) throws Throwable {
  241. int n = args.length - 1;
  242. if (n >= 0) {
  243. String[] args2 = new String[n];
  244. for (int i = 0; i < n; ++i)
  245. args2[i] = args[i + 1];
  246. run(args[0], args2);
  247. }
  248. }
  249. /**
  250. * Loads a class and calls <code>main()</code> in that class.
  251. *
  252. * @param classname the loaded class.
  253. * @param args parameters passed to <code>main()</code>.
  254. */
  255. public void run(String classname, String[] args) throws Throwable {
  256. Class c = loadClass(classname);
  257. try {
  258. c.getDeclaredMethod("main", new Class[] { String[].class }).invoke(
  259. null,
  260. new Object[] { args });
  261. }
  262. catch (java.lang.reflect.InvocationTargetException e) {
  263. throw e.getTargetException();
  264. }
  265. }
  266. /**
  267. * Requests the class loader to load a class.
  268. */
  269. protected Class loadClass(String name, boolean resolve)
  270. throws ClassFormatError, ClassNotFoundException {
  271. Class c = findLoadedClass(name);
  272. if (c == null)
  273. c = loadClassByDelegation(name);
  274. if (c == null)
  275. c = findClass(name);
  276. if (c == null)
  277. c = delegateToParent(name);
  278. if (resolve)
  279. resolveClass(c);
  280. return c;
  281. }
  282. /**
  283. * Finds the specified class using <code>ClassPath</code>.
  284. * If the source throws an exception, this returns null.
  285. *
  286. * <p>This method can be overridden by a subclass of
  287. * <code>Loader</code>. Note that the overridden method must not throw
  288. * an exception when it just fails to find a class file.
  289. *
  290. * @return null if the specified class could not be found.
  291. * @throws ClassNotFoundException if an exception is thrown while
  292. * obtaining a class file.
  293. */
  294. protected Class findClass(String name) throws ClassNotFoundException {
  295. byte[] classfile;
  296. try {
  297. if (source != null) {
  298. if (translator != null)
  299. translator.onLoad(source, name);
  300. try {
  301. classfile = source.get(name).toBytecode();
  302. }
  303. catch (NotFoundException e) {
  304. return null;
  305. }
  306. }
  307. else {
  308. String jarname = "/" + name.replace('.', '/') + ".class";
  309. InputStream in = this.getClass().getResourceAsStream(jarname);
  310. if (in == null)
  311. return null;
  312. classfile = ClassPoolTail.readStream(in);
  313. }
  314. }
  315. catch (Exception e) {
  316. throw new ClassNotFoundException(
  317. "caught an exception while obtaining a class file for "
  318. + name, e);
  319. }
  320. int i = name.lastIndexOf('.');
  321. if (i != -1) {
  322. String pname = name.substring(0, i);
  323. if (getPackage(pname) == null)
  324. try {
  325. definePackage(
  326. pname, null, null, null, null, null, null, null);
  327. }
  328. catch (IllegalArgumentException e) {
  329. // ignore. maybe the package object for the same
  330. // name has been created just right away.
  331. }
  332. }
  333. return defineClass(name, classfile, 0, classfile.length);
  334. }
  335. protected Class loadClassByDelegation(String name)
  336. throws ClassNotFoundException
  337. {
  338. /* The swing components must be loaded by a system
  339. * class loader.
  340. * javax.swing.UIManager loads a (concrete) subclass
  341. * of LookAndFeel by a system class loader and cast
  342. * an instance of the class to LookAndFeel for
  343. * (maybe) a security reason. To avoid failure of
  344. * type conversion, LookAndFeel must not be loaded
  345. * by this class loader.
  346. */
  347. Class c = null;
  348. if (doDelegation)
  349. if (name.startsWith("java.")
  350. || name.startsWith("javax.")
  351. || name.startsWith("sun.")
  352. || name.startsWith("com.sun.")
  353. || name.startsWith("org.w3c.")
  354. || name.startsWith("org.xml.")
  355. || notDelegated(name))
  356. c = delegateToParent(name);
  357. return c;
  358. }
  359. private boolean notDelegated(String name) {
  360. if (notDefinedHere.get(name) != null)
  361. return true;
  362. int n = notDefinedPackages.size();
  363. for (int i = 0; i < n; ++i)
  364. if (name.startsWith((String)notDefinedPackages.elementAt(i)))
  365. return true;
  366. return false;
  367. }
  368. protected Class delegateToParent(String classname)
  369. throws ClassNotFoundException
  370. {
  371. ClassLoader cl = getParent();
  372. if (cl != null)
  373. return cl.loadClass(classname);
  374. else
  375. return findSystemClass(classname);
  376. }
  377. protected Package getPackage(String name) {
  378. return super.getPackage(name);
  379. }
  380. /*
  381. // Package p = super.getPackage(name);
  382. Package p = null;
  383. if (p == null)
  384. return definePackage(name, null, null, null,
  385. null, null, null, null);
  386. else
  387. return p;
  388. }
  389. */
  390. }