Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Loader.java 15KB

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