在 Java 中查找对象的包
可以使用类加载器的 getPackage() 方法获取类的对象的包。如果类加载器未创建包对象,则返回 null。
以下是一个展示此功能的程序 −
示例
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
System.out.println("The package is: " + new ArrayList().getClass().getPackage().getName());
System.out.println("The package is: " + new LinkedList().getClass().getPackage().getName());
System.out.println("The package is: " + new HashSet().getClass().getPackage().getName());
System.out.println("The package is: " + "This is a string".getClass().getPackage().getName());
System.out.println("The package is: " + new Double(1).getClass().getPackage().getName());
System.out.println("The package is: " + new Integer(1).getClass().getPackage().getName());
}
}输出
The package is: java.util The package is: java.util The package is: java.util The package is: java.lang The package is: java.lang The package is: java.lang
现在让我们了解一下上面的程序。
使用 getClass().getPackage().getName() 获取并打印包。以下代码片段演示了这一点 −
System.out.println("The package is: " + new ArrayList().getClass().getPackage().getName());
System.out.println("The package is: " + new LinkedList().getClass().getPackage().getName());
System.out.println("The package is: " + new HashSet().getClass().getPackage().getName());
System.out.println("The package is: " + "This is a string".getClass().getPackage().getName());
System.out.println("The package is: " + new Double(1).getClass().getPackage().getName());
System.out.println("The package is: " + new Integer(1).getClass().getPackage().getName());
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP