java输出完全限定名,在Java中使用完全限定名称和导入之间的区别

博客探讨了Java中使用内联导入(完全限定名)和普通导入在性能、内存、编译时间等方面是否存在差异。指出应主要关注可读性,多数情况下普通导入更优,特殊情况内联导入可避免混淆。还通过字节码证明二者性能相同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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("."));

and

import java.io.File;

...

chooser.setCurrentDirectory(new File("."));

解决方案

The main thing you should focus in is readability. I find the second one more readable.

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."":()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."":()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."":(Ljava/lang/String;)V

18: invokevirtual #7 // Method javax/swing/JFileChooser.setCurrentDirectory:(Ljava/io/File;)V

21: return

}

This is the bytecode for the second:

public class java8.tests.General {

public java8.tests.General();

Code:

0: aload_0

1: invokespecial #1 // Method java/lang/Object."":()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."":()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."":(Ljava/lang/String;)V

18: invokevirtual #7 // Method javax/swing/JFileChooser.setCurrentDirectory:(Ljava/io/File;)V

21: return

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值