Java.lang.Package class in Java

Java 2 added a class called Package that encapsulates version data associated with a package. Package version information is becoming more important because of the proliferation of packages and because a java program may need to know what version of a package is available.
This versioning information is retrieved and made available by the ClassLoader instance that loaded the class(es). Typically, it is stored in the manifest that is distributed with the classes. It extends class Object and implements AnnotatedElement.

Methods:

  1. getAnnotation(Class annotationClass): Returns this element’s annotation for the specified type if such an annotation is present, else null.

    Syntax: public  A getAnnotation(Class annotationClass)
    Returns: this element's annotation for the specified 
    annotation type if present on this element, else null.
    Exception: NullPointerException - if the given annotation class is null.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating getAnnotation() method 
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.reflect.Method;
      
    // declare a annotation type
    @Retention(RetentionPolicy.RUNTIME)
    @interface Demo 
    {
       String str();
       int val();
    }
      
    public class PackageDemo 
    {
      
       // setting values for the annotation
       @Demo(str = " Gfg Demo Annotation", val = 100)
         
       // a method to call in the main
       public static void gfg() throws NoSuchMethodException 
       {
          PackageDemo ob = new PackageDemo();
      
            
             Class c = ob.getClass();
      
             // get the method example
             Method m = c.getMethod("gfg");
      
             // get the annotation for class Demo
             Demo annotation = m.getAnnotation(Demo.class);
      
             // checking the annotation
             System.out.println(annotation.str() + " " + annotation.val());
        
         
       public static void main(String args[]) throws Exception
       {
          gfg();
       }
    }

    chevron_right

    
    

    Output:

    Gfg Demo Annotation 100
    
  2. Annotation[] getAnnotations(): Returns all annotations present on this element. (Returns an array of length zero if this element has no annotations.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.

    Syntax: public Annotation[] getDeclaredAnnotations().
    Returns: All annotations directly present on this element.
    Exception: NA.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating getAnnotation() method
    import java.lang.annotation.Annotation;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.reflect.Method;
      
          
    // declare a annotation type
    @Retention(RetentionPolicy.RUNTIME)
    @interface Demo 
    {
       String str();
       int val();
    }
      
    public class PackageDemo 
    {
      
       // setting values for the annotation
       @Demo(str = " Gfg Demo Annotation", val = 100)
         
       // a method to call in the main
       public static void gfg() throws NoSuchMethodException 
       {
          PackageDemo ob = new PackageDemo();
      
            
             Class c = ob.getClass();
      
             // get the method example
             Method m = c.getMethod("gfg");
      
             // get the annotation for class Demo
             Demo annotation = m.getAnnotation(Demo.class);
      
             // checking the annotation
             System.out.println(annotation.str() + " " + annotation.val());
             Annotation[] gfg_ann = m.getAnnotations();
               
             for(int i = 0; i < gfg_ann.length; i++)
             {
                 System.out.println(gfg_ann[i]);
             }
        
         
       public static void main(String args[]) throws Exception
       {
          gfg();
       }
    }

    chevron_right

    
    

    Output:

    Gfg Demo Annotation 100
    @Demo(str= Gfg Demo Annotation, val=100)
    
  3. Annotation[] getDeclaredAnnotations(): Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.

    Syntax: public Annotation[] getDeclaredAnnotations().
    Returns: All annotations directly present on this element.
    Exception: NA.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // java code illustrating getDeclaredAnnotation() method
    import java.lang.annotation.Annotation;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.reflect.Method;
      
    // declare a annotation type
    @Retention(RetentionPolicy.RUNTIME)
    @interface Demo 
    {
       String str();
       int val();
    }
      
    public class PackageDemo 
    {
      
       // setting values for the annotation
       @Demo(str = " Gfg Demo Annotation", val = 100)
         
       // a method to call in the main
       public static void gfg() throws NoSuchMethodException 
       {
          PackageDemo ob = new PackageDemo();
      
            
             Class c = ob.getClass();
      
             // get the method example
             Method m = c.getMethod("gfg");
      
             // get the annotation for class Demo
             Demo annotation = m.getAnnotation(Demo.class);
      
             // checking the annotation
             System.out.println(annotation.str() + " " + annotation.val());
             Annotation[] gfg_ann = m.getDeclaredAnnotations();
               
             for(int i = 0; i < gfg_ann.length; i++)
             {
                 System.out.println(gfg_ann[i]);
             }
        
         
       public static void main(String args[]) throws Exception
       {
          gfg();
       }
    }

    chevron_right

    
    

    Output:

     Gfg Demo Annotation 100
    @Demo(str= Gfg Demo Annotation, val=100)
    
  4. String getImplementationTitle(): Return the title of this package.

    Syntax: public String getImplementationTitle()
    Returns: the title of the implementation, null is returned if it is not known.
    Exception: NA
    
  5. String getImplementationVersion(): Return the version of this implementation. It consists of any string assigned by the vendor of this implementation and does not have any particular syntax specified or expected by the Java runtime. It may be compared for equality with other package version strings used for this implementation by this vendor for this package.

    Syntax: public String getImplementationVersion()
    Returns: the version of the implementation, null is returned if it is not known.
    Exception: NA
    
  6. String getImplementationVendor(): Returns the name of the organization, vendor or company that provided this implementation.

    Syntax: public String getImplementationVendor().
    Returns: the vendor that implemented this package.
    Exception: NA.
    
  7. String getName(): Return the name of this package.

    Syntax: public String getName()
    Returns: The fully-qualified name of this package as defined
     in section 6.5.3 of The Java™ Language Specification, for example, java.lang.
    Exception: NA
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating getName(), getImplementationTitle()
    // and getImplementationVendor() and getImplementationVersion()
    // methods
    class PackageDemo
    {
        public static void main(String arg[])
        {
            Package pkgs[];
            pkgs = Package.getPackages();
              
            for(int i=0; i<1; i++)
            {
                //  name of the package
                System.out.println(pkgs[i].getName());
                  
                // checking title of this implementation
                System.out.println(pkgs[i].getImplementationTitle());
                  
                // checking the vendor
                System.out.println(pkgs[i].getImplementationVendor());
                  
                // version of this implementation
                System.out.println(pkgs[i].getImplementationVersion());
                              
            }
        }
    }

    chevron_right

    
    

    Output:

    sun.reflect
    Java Runtime Environment
    Oracle Corporation
    1.8.0_121
    
  8. static Package getPackage(String name): Find a package by name in the callers ClassLoader instance. The callers ClassLoader instance is used to find the package instance corresponding to the named class. If the callers ClassLoader instance is null then the set of packages loaded by the system ClassLoader instance is searched to find the named package.

    Syntax: public static Package getPackage(String name)
    Returns: the package of the requested name. It may 
    be null if no package information is available from the archive or 
    codebase.
    Exception: NA
    
  9. static Package[] getPackages(): Get all the packages currently known for the caller’s ClassLoader instance. Those packages correspond to classes loaded via or accessible by name to that ClassLoader instance. If the caller’s ClassLoader instance is the bootstrap ClassLoader instance, which may be represented by null in some implementations, only packages corresponding to classes loaded by the bootstrap ClassLoader instance will be returned.

    Syntax: public static Package[] getPackages()
    Returns: a new array of packages known to the callers 
    ClassLoader instance. An zero length array is returned if none are known.
    Exception: NA
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating getPackages() method
    class PackageDemo
    {
        public static void main(String arg[])
        {
            Package pkgs[];
            pkgs = Package.getPackages();
              
            Package pkg = Package.getPackage("java.lang");
              
            for(int i=0; i<1; i++)
            {
            System.out.println(pkg.getName());
            System.out.println(pkgs[i].getName());
            }
        }
    }

    chevron_right

    
    

    Output:

    java.lang
    sun.reflect
    
  10. String getSpecificationTitle(): Return the title of the specification that this package implements.

    Syntax: public String getSpecificationTitle()
    Returns: the specification title, null is returned 
    if it is not known.
    exception: NA.
    
  11. String getSpecificationVersion(): Returns the version number of the specification that this package implements. This version string must be a sequence of nonnegative decimal integers separated by “.”‘s and may have leading zeros. When version strings are compared the most significant numbers are compared.

    Syntax: public String getSpecificationVersion().
    Returns: the specification version, null is returned 
    if it is not known.
    Exception: NA.
    
  12. String getSpecificationVendor(): Return the name of the organization, vendor, or company that owns and maintains the specification of the classes that implement this package.

    Syntax: public String getSpecificationVendor()
    Returns: the specification vendor, null is returned
     if it is not known.
    Exception: NA.
    
  13. int hashCode(): Return the hash code computed from the package name.

    Syntax: Return the hash code computed from the package name.
    Exception: NA
    Returns: the hash code.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating hashCode(), getSpecificationTitle()
    // getSpecificationVendor() and getSpecificationVersion()
    class PackageDemo
    {
        public static void main(String arg[])
        {
            Package pkgs[];
            pkgs = Package.getPackages();
              
            for(int i=0; i<1; i++)
            {
                //  name of the package
                System.out.println(pkgs[i].hashCode());
                  
                // checking title 
                System.out.println(pkgs[i].getSpecificationTitle());
                  
                // checking the vendor
                System.out.println(pkgs[i].getSpecificationVendor());
                  
                // checking version
                System.out.println(pkgs[i].getSpecificationVersion());
                              
            }
        }
    }

    chevron_right

    
    

    Output:

    685414683
    Java Platform API Specification
    Oracle Corporation
    1.8
    
  14. boolean isCompatibleWith(String desired): Compare this package’s specification version with a desired version. It returns true if this packages specification version number is greater than or equal to the desired version number.

    Syntax: public boolean isCompatibleWith(String desired).
    Returns: true if this package's version number is 
    greater than or equal to the desired version number
    Exception: 
    NumberFormatException - if the desired or current version is not 
    of the correct dotted form.
    
  15. boolean isSealed(): Returns true if this package is sealed.

    Syntax: public boolean isSealed()
    Returns: true if the package is sealed, false otherwise.
    Exception: NA
    
  16. boolean isSealed(URL url): Returns true if this package is sealed with respect to the specified code source url.

    Syntax: public boolean isSealed(URL url)
    Returns: true if this package is sealed with respect to url
    Exception: NA
    
  17. String toString(): Returns the string representation of this Package. Its value is the string “package ” and the package name. If the package title is defined it is appended. If the package version is defined it is appended.

    Syntax: public String toString()
    Returns: the string representation of the package.
    Exception: NA
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // java code illustrating isCompatibleWith(), toString(),
    // isSealed methods
      
    import java.net.MalformedURLException;
    import java.net.URL;
      
    class PackageDemo
    {
        public static void main(String arg[]) throws MalformedURLException
        {
            Package pkg = Package.getPackage("java.lang");
              
            // checking if pkg is compatible with 1.0
            System.out.println(pkg.isCompatibleWith("1.0"));
              
            // checking if packet is sealed
            System.out.println(pkg.isSealed());
              
            URL url = new URL("https://www.youtube.com/");
              
            System.out.println(pkg.isSealed(url));
              
            // string equivalent of package
            System.out.println(pkg.toString());
              
        }
    }

    chevron_right

    
    

    Output:

    true
    false
    false
    package java.lang, Java Platform API Specification, version 1.8
    

This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.