k.stm
k.stm

Reputation: 200

Accessing top level classes from within a Java package

Say we have a project located at folder project with the sources in project/src.

We have a package package at project/src/package and classes

Now we want to evoke the constructor of TopClass inside of PackageClass, but said constructor (although declared public) seems to be not invisible inside of the package.

Do we need to import it somehow? How can we access it?

Upvotes: 1

Views: 904

Answers (1)

Ben Win
Ben Win

Reputation: 840

It is specified that it is a compile time error to import a type from the unnamed package.

So to archieve what you are trying to do, you have to use some kind of indirect class access, like reflections API:

Class sampleClass = Class.forName("SampleClass");
Method sampleMethod = sampleClass.getMethod("sampleMethod" , new Class[] { String.class });
sampleMethod.invoke(sampleClass.newInstance(), "It works!");

with the default package class:

public class SampleClass {
    public void sampleMethod(String str) {
        System.out.println(str);
    }
}

Upvotes: 1

Related Questions