/** * Find a package by name in the callers {@code ClassLoader} instance. The callers {@code * ClassLoader} instance is used to find the package instance corresponding to the named class. If * the callers {@code ClassLoader} instance is null then the set of packages loaded by the system * {@code ClassLoader} instance is searched to find the named package. * * <p>Packages have attributes for versions and specifications only if the class loader created * the package instance with the appropriate attributes. Typically, those attributes are defined * in the manifests that accompany the classes. * * @param name a package name, for example, java.lang. * @return the package of the requested name. It may be null if no package information is * available from the archive or codebase. */ public static Package getPackage(String name) { ClassLoader l = ClassLoader.getCallerClassLoader(); if (l != null) { return l.getPackage(name); } else { return getSystemPackage(name); } }
/** * Returns the {@code Package} of which the class represented by this {@code Class} is a member. * Returns {@code null} if no {@code Package} object was created by the class loader of the class. * * @return Package the {@code Package} of which this {@code Class} is a member or {@code null}. */ public Package getPackage() { // TODO This might be a hack, but the VM doesn't have the necessary info. ClassLoader loader = getClassLoader(); if (loader != null) { String name = getName(); int dot = name.lastIndexOf('.'); return (dot != -1 ? loader.getPackage(name.substring(0, dot)) : null); } return null; }
/** * Get the package for the specified class. The class's class loader is used to find the package * instance corresponding to the specified class. If the class loader is the bootstrap class * loader, which may be represented by {@code null} in some implementations, then the set of * packages loaded by the bootstrap class loader is searched to find the package. * * <p>Packages have attributes for versions and specifications only if the class loader created * the package instance with the appropriate attributes. Typically those attributes are defined in * the manifests that accompany the classes. * * @param class the class to get the package of. * @return the package of the class. It may be null if no package information is available from * the archive or codebase. */ static Package getPackage(Class<?> c) { String name = c.getName(); int i = name.lastIndexOf('.'); if (i != -1) { name = name.substring(0, i); ClassLoader cl = c.getClassLoader(); if (cl != null) { return cl.getPackage(name); } else { return getSystemPackage(name); } } else { return null; } }
public Package getPackage() { ClassLoader cl = type.getClassLoader(); return cl.getPackage(getPackageName()); }