Can I create a custom java.* package?

2019-05-06 00:52发布

Can I create a package of my own that has the same name as a predefined package
in Java, such as java.lang?

If so, what would the results be? Wouldn't that enable me to access that package's protected members?

If not, what prevents me from doing so?

标签: java packages
3条回答
别忘想泡老子
2楼-- · 2019-05-06 01:07

Any package name matching "java.*" is prohibited and a security exception will be thrown.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-05-06 01:08

There are two things preventing you.

1) The license agreement. "Note: Applications that use this option for the purpose of overriding a class in rt.jar should not be deployed as doing so would contravene the Java 2 Runtime Environment binary code license." http://download.oracle.com/javase/6/docs/technotes/tools/windows/java.html

2) You have to use the -Xbootclasspath:bootclasspath or add a lib/endorsed directory.

Some classes are not easily modified due to internal optimisations in the JVM e.g. you cannot add more than one method to Object to Sun/Oracle's JVM ;)

查看更多
趁早两清
4楼-- · 2019-05-06 01:09

No - java.lang is prohibited. The security manager doesn't allow "custom" classes in the java.lang package and there is no way telling him to accept them.

You're right - own classes declared in the java.lang namespace would allow you to use protected methods and members of classes in that package, and this is definitly not wanted.


This compiles fine - but - try to execute it ;)

package java.lang;

public class EvilAsEvilCanBe {

    public static void main(String[] args) {
        System.out.println("hehe");
    }

}
查看更多
登录 后发表回答