Package level method

Is it possible to write a method available at the package level? Suppose foo is a package:

 long version = foo.getPackageVersion(); 
+4
source share
4 answers

No, it is not. Methods can only be defined for classes. Nowhere.

A packet is not physical; it cannot serve as a container for byte code. Packages are just namespaces for classes, enumerations, and interfaces.

+6
source

You can do this in scala, but it creates a class to store these methods and package-level objects.

You can create javadocs at the package level and add annotations to it, but not fields, constructors, or methods.

In a file named package-info.java in mypackage package

 /** * Javadoc comments for package {@code mypackage}. */ @PackageVersion(getPackageVersion = "1.2.3") package mypackage; 

 @Retention(RetentionPolicy.RUNTIME) public @interface PackageVersion { String getPackageVersion(); } 

 Package mypackage = Package.getPackage("mypackage"); PackageVersion version = mypackage.getAnnotation(PackageVersion.class); System.out.println("Package version: "+version.getPackageVersion()); 

prints

 Package version: 1.2.3 

This object was added in JSR-175.

+6
source

No. Packages cannot be either objects themselves or classes. Only classes have methods.

0
source

In Java, Methods / Operations must be inside a class. The compiler complains if you try to add a method outside the class.

0
source

All Articles