How to make the jvm load my java.lang.String instead of the one in rt.jar

可紊 提交于 2019-11-28 01:34:48

问题


I studied java classloader rencently. Now I want to write a class that has the same package name and class name as one of class in rt.jar. For example, write a java.lang.String class by myself, and how to break the parents delegation model to make the jvm load my java.lang.String instead of the one in rt.jar.

Re-edit
Thx, tried. And ↓↓↓


    D:\>java -verbose -Xbootclasspath/p:D:/myrt.jar -jar exe.jar
    [Opened D:\myrt.jar]
    [Opened C:\java\jre\lib\rt.jar]
    [Loaded java.lang.Object from C:\java\jre\lib\rt.jar]
    [Loaded java.lang.String from D:\myrt.jar]
    [Loaded java.io.Serializable from C:\java\jre\lib\rt.jar]
    [Loaded java.lang.reflect.GenericDeclaration from C:\java\jre\lib\rt.jar]
    [Loaded java.lang.reflect.Type from C:\java\jre\lib\rt.jar]
    [Loaded java.lang.reflect.AnnotatedElement from C:\java\jre\lib\rt.jar]
    [Loaded java.lang.Class from C:\java\jre\lib\rt.jar]
    Invalid layout of java.lang.String at value
    #
    # A fatal error has been detected by the Java Runtime Environment:
    #
    #  Internal Error (javaClasses.cpp:136), pid=6968, tid=4116
    #  fatal error: Invalid layout of preloaded class
    #
    # JRE version:  (7.0_45-b18) (build )
    # Java VM: Java HotSpot(TM) 64-Bit Server VM (24.45-b08 mixed mode windows-amd64
     compressed oops)
    # Failed to write core dump. Minidumps are not enabled by default on client vers
    ions of Windows
    #
    # An error report file with more information is saved as:
    # D:\\hs_err_pid6968.log
    #
    # If you would like to submit a bug report, please visit:


回答1:


You can do this using the -Xbootclasspath/p option at JVM startup:

-Xbootclasspath/p:/path/to/yourimpl.jar

/p stands for "prepend".

Note: -Xbootclasspath isn't a standard java option, so JVMs by different vendors may not support it.




回答2:


Have a look at the java.lang.instrumentation API: you can implement a ClassFileTransformer which ignores the passed-in byte array and returns a bute array containing your own implementation of java.lang.String instead.

Better make sure that it's completely binary compatible with the original though or you will not get very far.



来源:https://stackoverflow.com/questions/22060752/how-to-make-the-jvm-load-my-java-lang-string-instead-of-the-one-in-rt-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!