Create an object with the. Class File

Source: Internet
Author: User

Step 1: Create an object for the compiled class file and its package name.

1) source code of the class file

Java code
  1. Package com. WSC. classloader;
  2. Public class tool {
  3. Public void print (){
  4. }
  5. }

2) use javac tool. Java to compile a class file

 

3) read the tool. Class file to the memory and generate a byte [] Array

Java code
  1. /**
  2. * Load the class file
  3. *
  4. * @ Param clazzpath
  5. * Class absolute file path
  6. * @ Return byte array
  7. * @ Throws ioexception
  8. */
  9. Private byte [] loadclassfile (string clazzpath) throws ioexception {
  10. Fileinputstream FCM = new fileinputstream (clazzpath );
  11. Bufferedinputstream Bis = new bufferedinputstream (FCM );
  12. Bytearrayoutputstream baos = new bytearrayoutputstream ();
  13. Byte [] buffer = new byte [1024*256];
  14. Int CH = 0;
  15. While (CH = bis. Read (buffer, 0, buffer. Length ))! =-1 ){
  16. Baos. Write (buffer, 0, CH );
  17. }
  18. Return baos. tobytearray ();
  19. }

4) customize classloader and use the defineclass method in classloader: protected final class <?> Defineclass (string name, byte [] B, int off, int Len ). The parameters are the class names, the byte array corresponding to the class file, the start position and the end position.

Java code
  1. @ Override
  2. Protected class <?> Loadclass (string name, Boolean resolve)
  3. Throws classnotfoundexception {
  4. Class <?> C = findloadedclass (name );
  5. If (C = NULL ){
  6. C = defineclass (name, Data, 0, Data. Length );
  7. }
  8. Return C;
  9. }

The overall code is:

Java code
  1. Package com. WSC. classloader;
  2. Import java. Io. bufferedinputstream;
  3. Import java. Io. bytearrayoutputstream;
  4. Import java. Io. fileinputstream;
  5. Import java. Io. ioexception;
  6. Public class classloaderone extends classloader {
  7. Public static void main (string [] ARGs) throws exception {
  8. Classloaderone loader = new classloaderone (
  9. "E: \ Java \ javafx \ classloader \ libs \ tool. Class ");
  10. Class <?> Clazz = loader. loadclass ("com. WSC. classloader. tool ");
  11. Object o = clazz. newinstance ();
  12. System. Out. println (O. getclass (). getclassloader ());
  13. }
  14. Private byte [] data;
  15. Public classloaderone (string clazzpath) throws ioexception {
  16. Data = loadclassfile (clazzpath );
  17. }
  18. /**
  19. * Load the class file
  20. *
  21. * @ Param clazzpath
  22. * Class absolute file path
  23. * @ Return byte array
  24. * @ Throws ioexception
  25. */
  26. Private byte [] loadclassfile (string clazzpath) throws ioexception {
  27. Fileinputstream FCM = new fileinputstream (clazzpath );
  28. Bufferedinputstream Bis = new bufferedinputstream (FCM );
  29. Bytearrayoutputstream baos = new bytearrayoutputstream ();
  30. Byte [] buffer = new byte [1024*256];
  31. Int CH = 0;
  32. While (CH = bis. Read (buffer, 0, buffer. Length ))! =-1 ){
  33. Baos. Write (buffer, 0, CH );
  34. }
  35. Return baos. tobytearray ();
  36. }
  37. @ Override
  38. Protected class <?> Loadclass (string name, Boolean resolve)
  39. Throws classnotfoundexception {
  40. Class <?> C = findloadedclass (name );
  41. If (C = NULL ){
  42. C = defineclass (name, Data, 0, Data. Length );
  43. }
  44. Return C;
  45. }
  46. }

It feels like this. Run the following command:

Java code
  1. Exception in thread "Main" Java. Lang. securityexception: prohibited package name: Java. Lang
  2. At java. Lang. classloader. predefineclass (unknown source)
  3. At java. Lang. classloader. defineclass (unknown source)
  4. At java. Lang. classloader. defineclass (unknown source)
  5. At com. WSC. classloader. classloaderone. loadclass (classloaderone. Java: 52)
  6. At java. Lang. classloader. loadclass (unknown source)
  7. At java. Lang. classloader. defineclass1 (native method)
  8. At java. Lang. classloader. defineclass (unknown source)
  9. At java. Lang. classloader. defineclass (unknown source)
  10. At com. WSC. classloader. classloaderone. loadclass (classloaderone. Java: 52)
  11. At java. Lang. classloader. loadclass (unknown source)
  12. At com. WSC. classloader. classloaderone. Main (classloaderone. Java: 14)

It means that the package named java. Lang cannot be loaded.

The reason is: although the tool class does not use any introduced Java. lang class, but its parent class object is in Java. in Lang, when the classloader loads the tool class, it loads all its relational networks. The parent class object must be loaded.

This is simple! You only need to write one more if else. Use the parent loader (each class loader has a parent class loader) to load.

Java code
  1. @ Override
  2. Protected class <?> Loadclass (string name, Boolean resolve)
  3. Throws classnotfoundexception {
  4. Class <?> C = findloadedclass (name );
  5. If (name. Equals ("Java. Lang. Object ")){
  6. Classloader parent = getparent ();
  7. C = parent. loadclass (name );
  8. }
  9. If (C = NULL ){
  10. C = defineclass (name, Data, 0, Data. Length );
  11. }
  12. Return C;
  13. }

The result is:

Java code
  1. Com. WSC. classloader. classloaderone @ ca470

Step 2: New Problems

Java code
  1. Method [] Methods = clazz. getmethods ();
  2. For (INT I = 0; I <methods. length; I ++ ){
  3. String name = methods [I]. getname ();
  4. System. Out. println (name );
  5. Class <?> [] Params = methods [I]. getparametertypes ();
  6. For (Int J = 0; j <Params. length; j ++ ){
  7. System. Out. println (Params [J]. tostring ());
  8. }
  9. }

At this time, the error will still be reported, because the method class is also under the java. lang Package, only one if else can be added.

Obviously, the code should be written like this

Java code
  1. @ Override
  2. Protected class <?> Loadclass (string name, Boolean resolve)
  3. Throws classnotfoundexception {
  4. Class <?> C = findloadedclass (name );
  5. If (C = NULL ){
  6. // If the parent loader is not null, use the parent loader to load (such as core classes such as object and hashmap)
  7. If (getparent ()! = NULL ){
  8. Try {
  9. C = getparent (). loadclass (name );
  10. } Catch (exception e ){
  11. // If the parent class is not loaded, an exception is thrown.
  12. }
  13. }
  14. // If the parent class loader is not loaded, use the custom loader to load it.
  15. If (C = NULL ){
  16. C = defineclass (name, Data, 0, Data. Length );
  17. }
  18. }
  19. Return C;
  20. }

Print result:

Java code
  1. Tostring
  2. Print
  3. Class java. Lang. String
  4. Getclass
  5. Hashcode
  6. Equals
  7. Class java. Lang. Object
  8. Notify
  9. Policyall
  10. Wait
  11. Long
  12. Int
  13. Wait
  14. Wait
  15. Long
  16. Com. WSC. classloader. classloaderone @ fcfa52

Step 3: If you can create a local file using the. Class file, the same principle applies to the remote file. (If you need to encrypt the file, you can decrypt it locally ). If the class file is called remotely, the local interface or reflection method is generally used. The first choice is the interface. The first choice is the efficiency, but it is too troublesome to know the names and parameters of all methods.

The remote loading of class files to the local machine makes it difficult to locate the error location if an error occurs. Fortunately, the use of classloader rules is used based on urlclassloader by default. The system first checks whether the class exists locally. Therefore, you can directly place the source code to debug it. Of course, you must delete it when releasing it.



You can use this basic getting started program to understand the basic process of classloader.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.