Say I am creating a class LangTest.java
in the following way:
package java.lang;
public class LangTest
{
public static void show()
{
System.out.println("In langTest.show()");
}
}
In another class I am even calling the method as:
LangTest.show();
None of them has given any compilation problem, yet at run-time it throws exception. --
Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.lang
at java.lang.ClassLoader.preDefineClass(ClassLoader.java:479)
at java.lang.ClassLoader.defineClass(ClassLoader.java:614)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at com.javatpoint.Test.main(Test.java:28)
This happens whenever you create a package name starting with "java.
".
My question is why we are not allowed to create a class in java.lang or similar? Moreover, why no compilation error was given in this case?
My question is why we are not allowed to create a class in java.lang or similar?
You can create a class there. But for security reasons a "normal" classloader will not let you load it, it only accepts them from the JDK's own core jar file. This is to protect Java users from running malicious code that could completely corrupt their system (undermine sandbox restrictions for example).
You have to implement your own JDK (or at least create your own version of runtime.jar) if you want to implement your own version of the java.*
classes.
Moreover, why no compilation error was given in this case?
Well, the JDK standard libraries also need to be compiled by the same Java compiler...