在Java中使用完全限定名称和导入之间的区别 [英] Difference between using fully qualified name and import in Java
问题描述
在Java中,在性能,内存,编译时间等方面,使用内联导入"(全限定名)和普通导入是否有任何区别?
Are there any differences using an "inline import" (a fully qualified name) and normal import in terms of performance, memory, compile-time, etc. in Java?
chooser.setCurrentDirectory(new java.io.File("."));
和
import java.io.File;
...
chooser.setCurrentDirectory(new File("."));
推荐答案
您应该关注的主要内容是可读性.我发现第二个更具可读性.
The main thing you should focus in is readability. I find the second one more readable.
在极少数情况下,我更喜欢第二种方法.让我们考虑以下情形:由于某种原因,我编写了一个类并将其命名为File
.我输入了File file = new File(...)
,IDE为我自动导入了java.io.File
.但是我不需要那种对象,我需要 my File
类.因此,与导入正确的类相比,我更喜欢内联导入它,只是其他用户不会与Java的File
类混淆.
In rare cases, I prefer the second approach. Let's consider the following scenario: For some reason, I wrote a class and named it File
. I typed File file = new File(...)
and my IDE auto-imported the java.io.File
for me. But I don't want that kind of object, I want my File
class. So instead of importing the correct class, I prefer inline-import it, just that other users won't get confused with the Java's File
class.
关于性能,它们完全相同,这就是证明-
Regarding the performance, they're exactly the same, and here's the proof -
这是为第一个代码段生成的字节码:
This is the bytecode generated for the first snippet:
public class java8.tests.General {
public java8.tests.General();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: new #2 // class javax/swing/JFileChooser
3: dup
4: invokespecial #3 // Method javax/swing/JFileChooser."<init>":()V
7: astore_1
8: aload_1
9: new #4 // class java/io/File
12: dup
13: ldc #5 // String .
15: invokespecial #6 // Method java/io/File."<init>":(Ljava/lang/String;)V
18: invokevirtual #7 // Method javax/swing/JFileChooser.setCurrentDirectory:(Ljava/io/File;)V
21: return
}
这是第二个字节码:
public class java8.tests.General {
public java8.tests.General();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: new #2 // class javax/swing/JFileChooser
3: dup
4: invokespecial #3 // Method javax/swing/JFileChooser."<init>":()V
7: astore_1
8: aload_1
9: new #4 // class java/io/File
12: dup
13: ldc #5 // String .
15: invokespecial #6 // Method java/io/File."<init>":(Ljava/lang/String;)V
18: invokevirtual #7 // Method javax/swing/JFileChooser.setCurrentDirectory:(Ljava/io/File;)V
21: return
}
这篇关于在Java中使用完全限定名称和导入之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!