简体   繁体   English

Java:如何排除java.lang类的隐式导入

[英]Java: How to Exclude Implicit Import of java.lang classes

例如,如果我想排除加载java.lang.String,我将如何去做?

Write your own compiler, that can compile this new, almost-Java language. 编写自己的编译器,可以编译这种几乎是Java的新语言。

In Java, Java中,

Code in a compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang . 编译单元中的代码自动访问其程序包中声明的所有类型,并且还自动导入预定义程序包java.lang声明的所有公共类型。

There is no way to disable that behavior. 没有办法禁用该行为。 And you don't need to; 而且您不需要; imports only affect compilation, and even if a type was (unwisely) named the same as a java.lang type, like Object , you can reference it with its fully qualified name in source code. 导入只会影响编译,即使类型(不明智地)与java.lang类型具有相同的名称(如Object ,也可以在源代码中使用其完全限定名称来引用它。

You're mixing up two topics. 您正在混淆两个主题。

The heading reads "How to Exclude Implicit Import of java.lang classes", and in the body you ask about "exclude loading java.lang.String". 该标题为“如何排除java.lang类的隐式导入”,在正文中您询问“排除加载java.lang.String”。

The automatic import of java.lang.* has no influence whatsoever on the runtime. java.lang.*的自动导入对运行时没有任何影响 It only allows you at compile-time to reference strings with the simple word String instead of the dot-construct java.lang.String . 它仅允许您在编译时使用简单单词String而不是点构造java.lang.String来引用字符串。

The class java.lang.String will be loaded if and only if your code needs it , no matter if you referenced it as String or as java.lang.String in your source code. 仅当您的代码需要它时 ,才会加载 java.lang.String类,无论您在源代码中将其引用为String还是java.lang.String

And I am VERY SURE that every Java program needs the String class, eg in its public static void main(String[] args) plus in lots of library classes. 而且我非常确定每个Java程序都需要String类,例如,在其public static void main(String[] args)加上许多库类中。

So, if you worry about memory footprint so much that loading the String class might become a problem, switch to a different language, eg K&R C from the 1970s. 因此,如果您担心内存占用过多,以至于无法加载String类,请切换到其他语言,例如1970年代的K&RC。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM