在一个目录中,我定义了以下文件A.java:
package test;
public class A {}
class B {
public void hello() {
System.out.println("Hello World");
}
}
如果我执行以下操作,请从其他目录:
import test.B;
public class X {
public static void main(String [] args) {
B b = new B();
b.hello();
}
}
并编译javac X.java
,我收到以下错误:
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();
^
我无法更改包测试中的来源。我该如何解决这个问题?
答案 0 :(得分:2)
默认访问修饰符或没有修饰符指定的成员只能在declared package
中访问,但不能在包外访问。所以在您的情况下B
是只能在名为package
的{{1}}内访问。详细了解Access Modifiers
。
如果您无法更改包测试中的来源。请将您的代码/类移至test
包。
答案 1 :(得分:2)
在Java中,有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
在您的情况下,B
具有无修饰符,这意味着它只能在类内部和包内部看到。因此,如果您创建的是其他包的类X
,则不会看到B
。
要访问B
,您需要定义与B
位于同一个包中的类,在您的情况下,该类是包test
。 < / p>
答案 2 :(得分:1)
使用反射:
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);
}
}