📜  Java Java类

📅  最后修改于: 2022-05-13 01:55:52.310000             🧑  作者: Mango

Java Java类

Java 2 添加了一个名为 Package 的类,它封装了与包关联的版本数据。由于包的激增以及Java程序可能需要知道可用的包版本,包版本信息变得越来越重要。
此版本信息由加载类的 ClassLoader 实例检索并提供。通常,它存储在与类一起分发的清单中。它扩展类 Object 并实现 AnnotatedElement。

方法:

  1. getAnnotation(Class annotationClass):如果存在这样的注释,则返回此元素的指定类型的注释,否则返回 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.
    
    // 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();
       }
    }
    

    输出:

    Gfg Demo Annotation 100
    
  2. Annotation[] getAnnotations():返回此元素上存在的所有注释。 (如果此元素没有注释,则返回长度为零的数组。)此方法的调用者可以自由修改返回的数组;它不会影响返回给其他调用者的数组。
    Syntax: public Annotation[] getDeclaredAnnotations().
    Returns: All annotations directly present on this element.
    Exception: NA.
    
    // 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();
       }
    }
    

    输出:

    Gfg Demo Annotation 100
    @Demo(str= Gfg Demo Annotation, val=100)
    
  3. Annotation[] getDeclaredAnnotations():返回所有直接出现在这个元素上的注解。与此接口中的其他方法不同,此方法忽略继承的注解。 (如果此元素上没有直接存在注释,则返回长度为零的数组。)此方法的调用者可以自由修改返回的数组;它不会影响返回给其他调用者的数组。
    Syntax: public Annotation[] getDeclaredAnnotations().
    Returns: All annotations directly present on this element.
    Exception: NA.
    
    // 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();
       }
    }
    

    输出:

    Gfg Demo Annotation 100
    @Demo(str= Gfg Demo Annotation, val=100)
    
  4. String getImplementationTitle():返回这个包的标题。
    Syntax: public String getImplementationTitle()
    Returns: the title of the implementation, null is returned if it is not known.
    Exception: NA
    
  5. String getImplementationVersion():返回此实现的版本。它由此实现的供应商分配的任何字符串组成,并且没有Java运行时指定或期望的任何特定语法。它可以与此供应商为此包用于此实现的其他包版本字符串进行比较是否相等。
    Syntax: public String getImplementationVersion()
    Returns: the version of the implementation, null is returned if it is not known.
    Exception: NA
    
  6. String getImplementationVendor():返回提供此实现的组织、供应商或公司的名称。
    Syntax: public String getImplementationVendor().
    Returns: the vendor that implemented this package.
    Exception: NA.
    
  7. String getName():返回这个包的名字。
    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
    
    // 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());
                              
            }
        }
    }
    

    输出:

    sun.reflect
    Java Runtime Environment
    Oracle Corporation
    1.8.0_121
    
  8. static Package getPackage(String name):在调用者 ClassLoader 实例中按名称查找包。调用者 ClassLoader 实例用于查找与命名类对应的包实例。如果调用者 ClassLoader 实例为空,则搜索由系统 ClassLoader 实例加载的包集以查找命名包。
    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():获取调用者的 ClassLoader 实例当前已知的所有包。这些包对应于通过该 ClassLoader 实例加载或按名称可访问的类。如果调用者的ClassLoader实例是bootstrap ClassLoader实例,在某些实现中可能用null表示,则只会返回bootstrap ClassLoader实例加载的类对应的包。
    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
    
    // 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());
            }
        }
    }
    

    输出:

    java.lang
    sun.reflect
    
  10. String getSpecificationTitle():返回此包实现的规范的标题。
    Syntax: public String getSpecificationTitle()
    Returns: the specification title, null is returned 
    if it is not known.
    exception: NA.
    
  11. String getSpecificationVersion():返回此包实现的规范的版本号。此版本字符串必须是由“.”分隔的非负十进制整数序列,并且可能有前导零。当比较版本字符串时,比较最重要的数字。
    Syntax: public String getSpecificationVersion().
    Returns: the specification version, null is returned 
    if it is not known.
    Exception: NA.
    
  12. String getSpecificationVendor():返回拥有并维护实现此包的类规范的组织、供应商或公司的名称。
    Syntax: public String getSpecificationVendor()
    Returns: the specification vendor, null is returned
     if it is not known.
    Exception: NA.
    
  13. int hashCode():返回根据包名计算的哈希码。
    Syntax: Return the hash code computed from the package name.
    Exception: NA
    Returns: the hash 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());
                              
            }
        }
    }
    

    输出:

    685414683
    Java Platform API Specification
    Oracle Corporation
    1.8
    
  14. boolean isCompatibleWith(String desired):将此包的规范版本与所需版本进行比较。如果此包规范版本号大于或等于所需的版本号,则返回 true。
    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():如果这个包是密封的,则返回 true。
    Syntax: public boolean isSealed()
    Returns: true if the package is sealed, false otherwise.
    Exception: NA
    
  16. boolean isSealed(URL url):如果此包相对于指定的代码源 url 是密封的,则返回 true。
    Syntax: public boolean isSealed(URL url)
    Returns: true if this package is sealed with respect to url
    Exception: NA
    
  17. String toString():返回此包的字符串表示形式。它的值是字符串“package”和包名。如果定义了包标题,则会附加它。如果定义了包版本,则附加它。
    Syntax: public String toString()
    Returns: the string representation of the package.
    Exception: NA
    
    // 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());
              
        }
    }
    

    输出:

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