Java中的类 getPackage() 方法和示例
Java.lang.Class 类的getPackage()方法用于获取该实体的包。这个实体可以是一个类、一个数组、一个接口等。方法返回这个实体的包。
句法:
public Package getPackage()
参数:此方法不接受任何参数。
返回值:该方法返回该实体的包。
下面的程序演示了 getPackage() 方法。
示例 1:
Java
// Java program to demonstrate getPackage() method
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Test");
System.out.println("Class represented by myClass: "
+ myClass.toString());
// Get the Package of myClass
// using getPackage() method
System.out.println("Package of myClass: "
+ myClass.getPackage());
}
}
Java
// Java program to demonstrate getPackage() method
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object
Class myClass = Class.forName("java.lang.String");
// Get the package of myClass
// using getPackage() method
System.out.println("Package of myClass: "
+ myClass.getPackage());
}
}
输出:
Class represented by myClass: class Test
Package of myClass: null
示例 2:
Java
// Java program to demonstrate getPackage() method
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object
Class myClass = Class.forName("java.lang.String");
// Get the package of myClass
// using getPackage() method
System.out.println("Package of myClass: "
+ myClass.getPackage());
}
}
输出:
Package of myClass: package java.lang,
Java Platform API Specification,
version 1.8
参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getPackage–