user1539577
user1539577

Reputation: 202

Creating an object of non-public class outside package

In one directory, I have defined the following file A.java:

package test; 
public class A {}
class B { 
    public void hello() {
        System.out.println("Hello World"); 
    }
}

From a different directory, if I do the following:

import test.B; 
public class X {
    public static void main(String [] args) {
        B b = new B(); 
        b.hello(); 
    }
}

and compile javac X.java, I get the following error:

X.java:2: test.B is not public in test; cannot be accessed from outside package
import test.B; 
         ^

X.java:7: test.B is not public in test; cannot be accessed from outside package
  B b  = new B();
  ^

X.java:7: test.B is not public in test; cannot be accessed from outside package
  B b  = new B();
             ^

I cannot change the sources in package test. How do I resolve this?

Upvotes: 2

Views: 3542

Answers (3)

ursa
ursa

Reputation: 4591

Use reflection:

package test2;

public class Main {
    public static void main(String[] args) throws Exception {
        java.lang.reflect.Constructor<?> bConstructor = Class.forName("test.B").getConstructor(/* parameter types */);
        bConstructor.setAccessible(true);
        Object b = bConstructor.newInstance(/* parameters */);

        java.lang.reflect.Method hello = b.getClass().getMethod("hello");
        hello.setAccessible(true);
        hello.invoke(b);
    }
}

Upvotes: 1

Akash Thakare
Akash Thakare

Reputation: 22972

Default access modifier OR no modifier specified member is only accessible in declared package but not outside the package.So in your case B is only accessible inside package named test. Read more on Access Modifiers.

If you cannot change the sources in package test.Than move your code/class to test package.

Upvotes: 2

Jean Logeart
Jean Logeart

Reputation: 53819

In Java, there are 4 different scope accessibilities:

Modifier    Class   Package Subclass    World
public        Y        Y       Y          Y
protected     Y        Y       Y          N
no modifier   Y        Y       N          N
private       Y        N       N          N

In your case, B has no modifier, which means it can be seen inside the class and inside the package only. Therefore, if you create class X that is an other package, it won't see B.

To acess B, you need to define a class that is inside the same package as B which in your case is the package test.

Upvotes: 2

Related Questions