Niklas R
Niklas R

Reputation: 16900

Method on package level

Is it possible to write a method that is available at package-level? Assume foo is a package:

long version = foo.getPackageVersion();

Upvotes: 4

Views: 489

Answers (4)

Reimeus
Reimeus

Reputation: 159864

No. Packages can be neither objects or classes themselves. Only classes have methods.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533870

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

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

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

/**
 * 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 facility was added in JSR-175

Upvotes: 6

kosa
kosa

Reputation: 66667

In Java Methods/Operations should be inside class. Compiler complains if you try to add a method outside the class.

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114817

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

A package is not physical, it can't serve as a container for byte code. Packages are nothing but namespaces for classes, enums and interfaces.

Upvotes: 6

Related Questions