Reputation: 200
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
TopClass
in project/src/TopClass.java
, andPackageClass
in project/src/package/PackageClass.java
.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
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