java代码获得类属于哪个包

java的Class类的getPackage()方法可以返回对象的包,使用包的getName()方法可以返回包名的字符串.

import java.util.ArrayList;
import java.util.Vector;
/**
 * Main.java
 *
 * @author outofmemory.cn
 */
public class Main {

    /**
     * Constructor
     */
    public Main() {

        findPackage(new Vector());
        findPackage(new ArrayList());

        findPackage("Test String");
        findPackage(new Integer(1));

    }

    /**
     * 打印对象属于哪个包
     *
     * @param testObject The object
     */
    public void findPackage(Object testObject) {

        System.out.println("Object has the package " + testObject.getClass().getPackage().getName());

    }

    /**
     * 启动应用程序
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main();
    }
}

上述代码执行结果如下:

Object has the package java.util
Object has the package java.util
Object has the package java.lang
Object has the package java.lang

posted on 2016-01-13 16:17  山冈龙  阅读(769)  评论(0编辑  收藏  举报

导航