簡體   English   中英

在包外創建非公共類的對象

[英]Creating an object of non-public class outside package

在一個目錄中,我定義了以下文件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();
             ^

我無法在套件測試中更改來源。 我該如何解決?

默認訪問修飾符沒有修飾符指定的成員只能在declared package訪問,而不能在包外部訪問。因此,在您的情況下, B只能在名為test package內部訪問。 閱讀更多有關Access Modifiers

如果您無法在test包中更改源代碼,則可以將代碼/類移至test包中。

在Java中,有4種不同的作用域可訪問性

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

使用反射:

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM