Java – custom string class creation

I tried to use Java. Net in my eclipse workspace Lang package to create a custom class string

Now I'm confused 1) why and 2) if allowed, why 3) If the creation of this type of Java class is allowed in Java, what will it be used for

Solution

You can use Java Create a new class in Lang package If Oracle developers are not allowed to develop java? I'm sure they use the same javac as we do

But you won't be able to load it because Java Lang. classloader (any classloader extension) does not allow it, and each loaded class passes this check

...
        if ((name != null) && name.startsWith("java.")) {
            throw new SecurityException
                ("Prohibited package name: " + name.substring(0,name.lastIndexOf('.')));
        }
...

So you'll end up with something like this

Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.lang
    at java.lang.ClassLoader.predefineClass(ClassLoader.java:649)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:785)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.urlclassloader.defineClass(urlclassloader.java:449)
    at java.net.urlclassloader.access$100(urlclassloader.java:71)
    at java.net.urlclassloader$1.run(urlclassloader.java:361)
    at java.net.urlclassloader$1.run(urlclassloader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.urlclassloader.findClass(urlclassloader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at Test1.main(Test1.java:11)

For classes that affect existing classes, such as your Java Lang. string, they cannot be loaded because system classloader (used by default) uses the "parent first" policy, so Java The Lang class will be loaded from rt.jar with the boot class loader So you need to replace your version of string. Jar in rt.jar class. Or override it with the - xbootclasspath / P: Java option, which adds the path to the boot classloader search path So you can

1) Set copybase to the real string Put Java content into your string In Java

2) Change the method, e.g

public static String valueOf(double d) {
    return "Hi";
}

And compile your string java

3) Create a test class

public class Test1 {

    public static void main(String[] args) throws Exception {
        System.out.println(String.valueOf(1.0d));
    }
}

4) Run it

java -Xbootclasspath/p:path_to_your_classes Test1

You'll see

Hi
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>